0

i'm wondering if it's possible to destructure the properties/methods from an instance of a class or function while maintaining scope across the destructured variables without having to use call() every time i need that method? For example:

class Pearson {}

Pearson.prototype.speak = function speak(){
  return this.sayHi
};

Pearson.prototype.speakOutLoud = function speakOutLoud(){
  return this.speak().toUpperCase()
};

const pearson = Object.assign(new Pearson(), {sayHi:"hi!!"});

const {speak, speakOutLoud} = pearson;

speak.call(pearson) // hi!!
speakOutLoud.call(pearson) // HI!!

I want to avoid the call() and i can't refactor and put all methods inside the class because i have a bunch of them, want to know if exist any cleaver solution to this.

Solution:

Bind "this" in the constructor

class Pearson {
    constructor(){
        this.speak = this.speak.bind(this)
        this.speakOutLoud = this.speakOutLoud.bind(this)
    }
}

Pearson.prototype.speak = function speak(){
  return this.sayHi
};

Pearson.prototype.speakOutLoud = function speakOutLoud(){
  return this.speak().toUpperCase()
};

const {speak} = Object.assign(new Pearson(), {sayHi:"hi!!"});

speak() // "hi!!"
  • Put everything into the class itself (don't assign to the prototype afterwards) and use arrow function class fields – CertainPerformance Mar 10 '22 at 01:50
  • @CertainPerformance thank you for your answer, but let suppose I am not allowed to modify the class only to extend it with proptypes, is there any other solution? – Jose Rodrigues Mar 10 '22 at 02:08

0 Answers0