You can rebind the 'grandchild' methods manually in the constructor:
bindAll = function(self, obj) {
Object.keys(obj).forEach(function(k) {
if(typeof obj[k] === 'function')
obj[k] = obj[k].bind(self);
});
}
var Model = function() {
bindAll(this, this.a);
this.x = 123;
};
Model.prototype.a = function() {}
Model.prototype.a.on = function() {
console.log(this.x);
}
var m = new Model();
m.a();
m.a.on();
A more memory-savvy way is to use an explicit pointer to the root class and consistently use this.root
instead of just this
in methods:
var Model = function(x) {
this.x = x;
this.model = this;
this.a = Object.create(this.a);
this.a.model = this;
};
Model.prototype.a = function() {
console.log(this.model.x);
}
Model.prototype.a.on = function() {
console.log(this.model.x);
};
var m1 = new Model(11), m2 = new Model(22);
m1.a.on();
m2.a.on();
m1.a.on();