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!!"