How to bind methods when destructuring an object in JavaScript? How to bind methods when destructuring an object in JavaScript? node.js node.js

How to bind methods when destructuring an object in JavaScript?


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.


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.

  1. 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(); //=> 5a();              //=> 5b();              //=> 5c();              //=> 5

  1. 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(); //=> 5a();              //=> 5b();              //=> 5c();              //=> 5


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] }