How to bind methods when destructuring an object in JavaScript?
You can use a getter or a proxy to bind a method whenever you get
it, even using destructuring.
Both solutions check if method is already bound, by looking for bound
at the start of the name using String.startsWith()
. If not bound, that method will be bound before returning it.
- Auto-bind the method to the object with a getter. This will require a getter for each method.
const person = {
prop: 5,
_getName: function() {
console.log(this.prop);
},
get getName() {
// if not bound, bind the method
if(!this._getName.name.startsWith('bound ')) {
this._getName = this._getName.bind(this);
}
return this._getName;
}
};
var a = person.getName;
var b = person.getName.bind(person);
var {getName: c} = person;
person.getName(); //=> 5
a(); //=> 5
b(); //=> 5
c(); //=> 5
- Auto-bind the method to the object with a proxy. Define once for all methods.
var handler = {
get: function(target, prop, receiver) {
// if method, and not bound, bind the method
if(typeof target[prop] === 'function' && !target[prop].name.startsWith('bound ')) {
target[prop] = target[prop].bind(target);
}
return target[prop];
}
};
const person = new Proxy({
prop: 5,
getName: function() {
console.log(this.prop);
}
}, handler);
var a = person.getName;
var b = person.getName.bind(person);
var {getName: c} = person;
person.getName(); //=> 5
a(); //=> 5
b(); //=> 5
c(); //=> 5
No, there is no way. Functions detached from objects lose the original context. And destructing in JavaScript has no syntax to do something with extracted values on the fly.