Function.prototype.bind.apply()无法按预期工作

时间:2015-04-19 22:09:22

标签: javascript functional-programming function-binding

我有一个函数myfunc,希望bindthis作为一个特定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' myfuncapply

通过bind致电bind,我错误地将bind分配给了{" mythis",这不是一个功能,无法调用myfunc.bind.apply(myfunc, ["mythis"].concat(["param1", "param2"]))

所以,解决方案是使用

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

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

addEventListener

但这不足以解决我的问题,因为我需要将绑定函数作为参数传递给{{1}}。

感谢您的帮助,伙计们!

3 个答案:

答案 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