Is there a way to rebind a function that is already bound to another object via Function.prototype.bind?
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 just wonder how to reuse an already bound function.
We use the Bind() method to call a function with the this value, this keyword refers to the same object which is currently selected . In other words, bind() method allows us to easily set which object will be bound by the this keyword when a function or method is invoked.
You can bind multiple arguments multiple times, exactly as partial application, but the context object only once, you can't override it once you bound it, because this is defined by specs that I linked: "The bind() function creates a new function (a bound function) with the same function body (internal call property in ...
bind() The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
In JavaScript, you can use call() , apply() , and bind() methods to couple a function with an object. This way you can call the function on the object as if it belonged to it. The call() and apply() are very similar methods. They both execute the bound function on the object immediately.
Is there a way to rebind a function that is already bound to another object via Function.prototype.bind?
No. From the ES2015 spec about Function.prototype.bind
:
19.2.3.2 Function.prototype.bind ( thisArg , ...args)
[...]
Note 2: If Target is an arrow function or a bound function then the thisArg passed to this method will not be used by subsequent calls to F.
This was already true for earlier versions as well.
What .bind()
does is almost the same as this:
function likeBind(fun, thisValue) {
return function() {
var args = [].slice.call(arguments, 0);
return fun.apply(thisValue, args);
};
}
So:
c = likeBind(c, a);
gives you a bound function. Now, even if you attempt to re-bind, the original bound function still exists in that closure with the value you originally requested to be used as this
. Values of variables inside closures can only be changed from inside the closure, so there's nothing you can do to un-bind a bound function like that. You have to start over from the original function.
So, no.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With