![](/img/trans.png)
[英]Getting Function.prototype.bind.apply(…) is not a constructor error
[英]Function.prototype.bind.apply() doesn't work as expected
我有一个函数myfunc
并希望bind
它bind
到特定的this
参数和其他参数bind
为单个数组,而不是参数列表(因为我将参数列表作为函数的参数,执行此代码)。 为此,我使用apply
on 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
on bind
我错误地将bind
的命名分配给了“mythis”,这不是一个函数,并且不能在它上面调用bind
。
所以,解决方案是使用
myfunc.bind.apply(myfunc, ["mythis"].concat(["param1", "param2"]))
此外,如果你想立即调用绑定的myfunc,你可以说:
myfunc.apply.bind(myfunc)("mythis", ["param1", "param2"])
但这不足以解决我的问题,因为我需要将绑定函数作为参数传递给addEventListener
。
谢谢你的帮助,伙计们!
您应该使用该函数作为apply
方法的第一个参数。 myfunc.bind
的使用不会将函数与调用相关联,它具有Function.prototype.bind
的效果,您也可以使用它。
bind
方法的第一个参数( thisArg
)应该是数组中的第一个项目。
var bindedMyfunc = Function.prototype.bind.apply(myfunc, ["mythis", "param1", "param2"]);
似乎绑定本身有自己的这个参数,它是函数,它被调用。 例如,当你说
myfunc.bind(args)
,bind
的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
参数:
(Function.prototype.apply).bind(myfunc, "mythis", ["param1", "param2"])
// which is equivalent to
(…args) => myfunc.apply("mythis", ["param1", "param2"], …args) // ES6 syntax
也许你想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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.