Since methods in Javascript can easily be rebound, some (many?) developers resorted to using JS's lexical scoping to achieve object encapsulation (i.e., private object state independent of the object the method is currently bound to). I found this particularly handy when working with promises like this:
function Something() {
const that = this; // optional
that.state = 0;
this.doSomething = function() {
console.log(that.state++);
};
return this;
}
const instance = new Something;
new Promise(resolve => resolve(instance)).then(instance.doSomething);
//output: 0
Unfortunately, this doesn't seem to be compatible with the current draft of Ecmascript 6 classes. This code:
class SomethingES6 {
constructor(){
this.state = 0;
}
doSomething(){
console.log(this.state++);
}
}
const instanceES6 = new SomethingES6;
new Promise(resolve => resolve(instanceES6)).then(instanceES6.doSomething);
Throws because the doSomething method isn't bound to instanceES6 when executed. Is there a way to achieve a behavior like the one exposed when exploiting the lexical scoping of "that" in the previous snippet?
I want a solution that enforces this behavior when defining the class - bluebird's (and other's) Promise.bind is not a solution! Personally I'd like a solution that works in node but, of course, a generic solution is preferable.