5

我有一个函数myfunc,希望将其作为单个数组而不是参数列表bind的特定this参数和其他参数(因为我将参数列表作为函数的参数,在其中执行此代码)。bind为此,我使用applyonbind如下:

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'sthismyfunc

通过调用applybind我错误地将bind's this 分配给了“mythis”,这不是一个函数,bind也不能在其上调用。

所以,解决方案是使用

myfunc.bind.apply(myfunc, ["mythis"].concat(["param1", "param2"]))

此外,如果您想立即调用绑定的 myfunc,您可以说:

myfunc.apply.bind(myfunc)("mythis", ["param1", "param2"])

但这还不够我的情况,因为我需要将绑定函数作为参数传递给addEventListener.

谢谢你们的帮助,伙计们!

4

3 回答 3

7

您应该使用该函数作为该apply方法的第一个参数。的使用myfunc.bind不会将函数与调用相关联,它具有 的效果Function.prototype.bind,您也可以使用它。

bind方法 ( )的第一个参数thisArg应该是数组中的第一项。

var bindedMyfunc = Function.prototype.bind.apply(myfunc, ["mythis", "param1", "param2"]);
于 2015-04-19T22:15:01.343 回答
3

似乎 bind 本身有自己的 this 参数,也就是函数,它被调用。例如,当你说myfunc.bind(args)bind'sthismyfunc

确切地。如果要应用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
于 2015-04-19T23:46:07.723 回答
2

也许你想bind apply而不是applying 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
于 2015-04-19T22:26:52.210 回答