Search code examples
javascriptfunctional-programmingfunction-binding

Function.prototype.bind.apply() doesn't work as expected


I've a function myfunc and want to bind it to a specific this argument and other arguments to bind as a single array, not parameters list (cause I get the parameters list as an argument of function, where this code is executed). For that purpose I use apply on bind as follows:

var myfunc = function(arg1, arg2){
    alert("this = " + this + ", arg1 = " + arg1 + ", arg2 = " + arg2);
}
var bindedMyfunc = myfunc.bind.apply("mythis", ["param1", "param2"]);
bindedMufunc();

This results in Uncaught TypeError: Bind must be called on a function.

What am I doing wrong? Could you explain in detail, what's going onwhen I run this code, cause reality seems to contradict my opinion on that?

Summary of answers: Seems that bind itself has its own this argument, which is the function, it is called on. E.g. when you say myfunc.bind(args), bind's this is myfunc.

By calling apply on bind I've mistakingly assigned bind's this to "mythis", which is not a function and bind can't be called on it.

So, the solution is to use

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

Also, if you want to call the binded myfunc right off, you could say:

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

but this doesn't suffice my case, cause I need to pass the binded function as an argument to addEventListener.

Thanks for your help, guys!


Solution

  • You should use the function as the first parameter to the apply method. The use of myfunc.bind doesn't associate the function with the call, it has the effect of Function.prototype.bind, and you can just as well use that.

    The first parameter for the bind method (thisArg) should be the first item in the array.

    var bindedMyfunc = Function.prototype.bind.apply(myfunc, ["mythis", "param1", "param2"]);