Reputation: 1390
Using Javascript prototype, how to get an instance property from another property of the same instance?
I am trying to call the Main.prototype.a
methods from the Main.prototype.b
methods.
I managed to solve this by adding an init
method on Main.prototype.b
that accepts an instance
variable and saves it as this.instance
which could later be used to refer to the instance in the other methods.
And then calling the init
method from the Main
constructor function while passing this
as the variable but I feel like I am missing a different more elegant and simple solution.
This is just a very simplified example of what I am trying to understand:
var Main = function(){}
Main.prototype.a = {
value: 1,
one: function(){
this.value++;
console.log("added 1", this.value);
},
two: function(){
this.value--;
console.log("reduced 1", this.value);
},
three: function(){
this.value+=10;
console.log("added 10", this.value);
}
}
Main.prototype.b = {
one: function(){
//call Main.prototype.a.one
},
two: function(){
//call Main.prototype.a.two
},
three: function(){
//call Main.prototype.a.three
},
getValue: function(){
//return Main.prototype.a.variable
}
}
var main = new Main();
Thank you for taking the time to read and to all who offers solutions in advance!
Upvotes: 0
Views: 36
Reputation: 15831
Simply:
var Main = function(){}
Main.prototype.a = {
value: 1,
one: function(){
this.value++;
console.log("added 1", this.value);
},
two: function(){
this.value--;
console.log("reduced 1", this.value);
},
three: function(){
this.value+=10;
console.log("added 10", this.value);
}
}
Main.prototype.b = {
one: function(){
Main.prototype.a.one();
},
two: function(){
//call Main.prototype.a.two
},
three: function(){
//call Main.prototype.a.three
},
getValue: function(){
//return Main.prototype.a.variable
}
}
var main = new Main();
main.b.one();
main.b.one();
Upvotes: 1