我刚刚在 JS 中经历了一个我无法理解的行为:我想创建一个方法来调用 String.prototype.replace 并给定一些参数,因此我想到了:
String.prototype.replace.bind("foo", /bar/g, function(){}).call
我猜想我会得到一个函数,我只需将一个字符串放入其中即可进行替换。相反,我总是得到返回的初始 this
值(在本例中为 foo
)。
现在我的问题是:
- 为什么 JS 会这样? bind 真正返回的是什么?如何获取
.call()
的this
参数? - 是否有另一种方法可以在不创建包装函数的情况下完成我想做的事情?
最佳答案
为什么会这样
您将 call
中的一些 this
值传递给 bind
返回的函数。然而,bind
会忽略该值并使用绑定(bind)的 this
(例如 foo
)调用原始函数。事实上,bind
意味着 绑定(bind)this
值。您可以绑定(bind)的 arguments
是一些额外的东西。
解决
如果没有包装函数,我不认为你可以做你想做的事。但是,使用包装器函数,您可以做您想做的事情:
Function.prototype.bindArgs = function() {
var args = arguments,
func = this;
return function(context) {
return func.apply(context, args);
}
};
例如
var func = function(a, b, c) {
console.log(this, a, b, c);
};
var bound = func.bindArgs(1, 2, 3);
bound([1]); // [1] 1 2 3
bound({a: 1}); // {a: 1} 1 2 3
关于javascript - 为什么 Function.bind ("foo").call ("bar") 总是将此引用到 "foo"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7213843/