我有一个函数myfunc
,希望将其作为单个数组而不是参数列表bind
的特定this
参数和其他参数(因为我将参数列表作为函数的参数,在其中执行此代码)。bind
为此,我使用apply
onbind
如下:
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
'sthis
是myfunc
。
通过调用apply
,bind
我错误地将bind
's this 分配给了“mythis”,这不是一个函数,bind
也不能在其上调用。
所以,解决方案是使用
myfunc.bind.apply(myfunc, ["mythis"].concat(["param1", "param2"]))
此外,如果您想立即调用绑定的 myfunc,您可以说:
myfunc.apply.bind(myfunc)("mythis", ["param1", "param2"])
但这还不够我的情况,因为我需要将绑定函数作为参数传递给addEventListener
.
谢谢你们的帮助,伙计们!