0

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!

Jake
  • 1,380
  • 3
  • 14
  • 27
  • [Don't put objects in inherited prototype properties](https://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects/) - especially not that `value`. You'll want to initialise it in the constructor. – Bergi Jul 04 '19 at 11:47

1 Answers1

1

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();
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43