I'm looking for a way to be able to do something like:
new A().b.c()
and have the scope (this) inside the c() method be that of the A prototype.
The only way I've found of doing that is to create the b property inside the A constructor and bind this to the function. I've very much like to be able to do it on the prototype, rather than in the constructor, for the performance benefits it would provide.
Does anyone know how this might be done, or is it simply not possible in Javascript?
Example here:
var A = function () {
this.isA = true;
}
A.prototype.b = {
c: function () {
console.log('isA:', this.isA);
}
}
// I would like this to result in `isA: true`
new A().b.c();
var M = function () {
this.isM = true;
this.b = {
c: function () {
console.log('isM', this.isM);
}.bind(this)
}
}
// It does here, but involes assignment in the constructor
new M().b.c();
thisto be the prototype object?? That's weird and would be really bad practice. I guess you mean something else. Can you provide a runnable snippet that outputs the wrong result, with an explanation of what the desired output is?thisto the function": which function? Instead of describing your attempt, can you provide the actual code you have used to achieve what you want? I would think you described puttingthis.b = thisin the constructor, but then I don't know what you are talking about when you say you "bind...to the function".bobject for everyAinstance, either in the constructor or dynamically upon access (with a getter on the prototype), that can refer back to the "parent" instance.