How to bind methods when destructuring an object in JavaScript?
const person = {
getName: function() {
console.log(this);
}
};
var a = person.getName;
var b = person.getName.bind(person);
var {getName: c} = person;
person.getName(); //=> {getName: [Function]}
a(); //=> window or global
b(); //=> {getName: [Function]}
c(); //=> window or global
I want c
to log in the console its "parent" object {getName:
[Function]}
.
Is there any way to bind all methods when destructuring an object in one destructuring line?
Destructuring on objects allows you to bind variables to different properties of an object. JavaScript provides two ways to destructure an object: 1.Destructuring an object with the same property names and variable names: One way to destructure an object is when the object property names and the local variable names are the same.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Destructuring objects with the same property names but different variable names. Another way to destructure an object is when the object property names and the local variable names are different. Let's understand the details with the help of the following example:
After the destructuring, the variable identifier contains the property value. rest variable is a plain object with the remaining properties. For example, let's extract the property name, but keep the rest of the properties: The destructuring const { name, ...realHero } = hero extracts the property name.
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.
There is a simple workaround using ES6 classes. You can use bind
in the class constructor to manually set the context of the function.
In the example below, getName()
will "survive" the destructuring :
class Person {
constructor() {
this.getName = this.getName.bind(this);
}
getName() {
console.log(this);
}
}
const {
getName
} = new Person();
getName(); // Person { getName: [Function: bound getName] }
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