Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind methods when destructuring an object in JavaScript?

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?

like image 664
Paweł Avatar asked Aug 27 '17 22:08

Paweł


People also ask

How to destruct an object in JavaScript?

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.

What is destructuring assignment in JavaScript?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

How to destruct an object with the same property names?

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:

What is the difference between destructuring and rest variable in JavaScript?

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.


2 Answers

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.

like image 104
Danil Speransky Avatar answered Sep 24 '22 04:09

Danil Speransky


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] }
like image 23
Ilshidur Avatar answered Sep 21 '22 04:09

Ilshidur