Javascript function binding function (how to link it to another object)

Is there a way to restore a function that is already bound to another object via the .prototype.bind function?

var a={}; var b={}; var c=function(){ alert(this===a); }; c(); // alerts false c=c.bind(a); c(); // alerts true c=c.bind(b); c(); // still alerts true 

I know that I can use a different approach and keep a β€œclean” function for binding, but I'm just wondering how to reuse an already linked function.

+7
javascript function bind
source share
2 answers

Is there a way to restore a function that is already bound to another object via the .prototype.bind function?

Not. From the ES2015 spec on Function.prototype.bind :

19.2.3.2 Function.prototype.bind (thisArg, ... args)

[...]

Note 2: If Target is an arrow function or a related function, then this attribute passed to this method will not be used by subsequent calls to F.

This was also true for earlier versions.

+6
source share

What .bind() does is pretty much the same:

 function likeBind(fun, thisValue) { return function() { var args = [].slice.call(arguments, 0); return fun.apply(thisValue, args); }; } 

So:

 c = likeBind(c, a); 

gives a related function. Now, even if you are trying to re-bind, the original bind function still exists in this closure with the value that you originally requested to use as this . The values ​​of the variables inside the closures can only be changed from within the closure, so you can’t do anything without binding a related function like this. You should start with the original feature.

So no .

+3
source share

All Articles