我有一个函数myfunc
,希望bind
将this
作为一个特定bind
参数和apply
的其他参数作为单个数组,而不是参数列表(因为我将参数列表作为函数的参数,执行此代码)。
为此,我在bind
上使用var myfunc = function(arg1, arg2){
alert("this = " + this + ", arg1 = " + arg1 + ", arg2 = " + arg2);
}
var bindedMyfunc = myfunc.bind.apply("mythis", ["param1", "param2"]);
bindedMufunc();
,如下所示:
Uncaught TypeError: Bind must be called on a function
这会产生bind
。
我做错了什么?你能详细解释一下,当我运行这段代码时会发生什么,导致现实似乎与我的看法相矛盾吗?
答案摘要:
似乎this
本身有自己的myfunc.bind(args)
参数,它是函数,它被调用。例如。当您说bind
时,this
' myfunc
为apply
。
通过bind
致电bind
,我错误地将bind
分配给了{" mythis",这不是一个功能,无法调用myfunc.bind.apply(myfunc, ["mythis"].concat(["param1", "param2"]))
。
所以,解决方案是使用
myfunc.apply.bind(myfunc)("mythis", ["param1", "param2"])
另外,如果你想立即调用绑定的myfunc,你可以说:
addEventListener
但这不足以解决我的问题,因为我需要将绑定函数作为参数传递给{{1}}。
感谢您的帮助,伙计们!
答案 0 :(得分:7)
您应该将该函数用作apply
方法的第一个参数。 myfunc.bind
的使用不会将函数与调用相关联,它具有Function.prototype.bind
的效果,您也可以使用它。
bind
方法的第一个参数(thisArg
)应该是数组中的第一个项目。
var bindedMyfunc = Function.prototype.bind.apply(myfunc, ["mythis", "param1", "param2"]);
答案 1 :(得分:3)
似乎绑定本身有自己的这个参数,它是函数,它被调用。例如。当您说
myfunc.bind(args)
时,bind
的{{1}}为this
。
完全。如果要应用myfunc
,则必须将其应用于函数(第一个参数),并将bind
参数(包括预期的bind
值)作为数组传递(第二个参数):
this
但是,还有另一种方法可以解决您的问题:将(Function.prototype.bind).apply(myfunc, ["mythis", "param1", "param2"])
// which is equivalent to
myfunc.bind("mythis", "param1", "param2")
(…args) => myfunc.call("mythis", "param1", "param2", …args) // ES6 syntax
绑定到函数,并部分应用建议的apply
参数:
apply
答案 2 :(得分:2)
也许您想要bind
apply
而不是apply
bind
?
var bindedMyfunc = Function.prototype.apply.bind(myfunc);
bindedMyfunc('obj', [1, 2]); // this = obj, arg1 = 1, arg2 = 2
我经常使用这种模式使hasOwnProperty
检查缩短而不会被隐藏;
var has = Function.prototype.call.bind(Object.hasOwnProperty);
has({foo:1}, 'foo'); // true
has({foo:1}, 'bar'); // false