Consider the following example:
var funcToCall = function() {...}.bind(importantScope);
// some time later
var argsToUse = [...];
funcToCall.apply(someScope, argsToUse);
I want to preserve ‘importantScope’ of funcToCall. Yet, I need to use apply to apply an unknown number of arguments. ‘apply’ requires that I provide ‘someScope’. I don’t want to change the scope, I just want to apply the arguments to the function and preserve its scope. How would I do that?
You can pass any old object (including
null) as the first argument to theapply()call andthiswill still beimportantScope.The
bindmethod creates a new function in which thethisvalue is guaranteed to be the object you passed in as the parameter to thebindcall. Regardless of how this new function is called,thiswill always be the same. A simple implementation would look like this (note the implementation specified ECMAScript 5 and that in Prototype does more than this but this should give you the idea):