Search code examples
javascriptobjectmethodsattributesprototype

How can I use attributes directly in methods of Javascript prototype?


I am used to coding with objects in different languages such as Java, Python, … I have never used JavaScript objects before and I am stuck with a problem: I don't know how to use attributes in methods.

I have done the following but perhaps it's not the correct way:

function test() {
  this.un = 1;
  this.deux = 2;
  this.sum = 1;

  add = function() {
    this.sum = this.un + this.deux;
  }
}

var test = new test();
console.log(test.sum); // res : 1
test.add;
console.log(test.sum); // res : 1 and not 3 as like i want


Solution

  • You have to call add as the method and declare it with this.add, like in the code snipet I posted:

    function test() {
      this.un = 1;
      this.deux = 2;
      this.sum = 1;
    
      this.add = function() {
        this.sum = this.un + this.deux;
      }
    }
    
    var obj = new test();
    console.log(obj.sum); // res : 1
    obj.add();
    console.log(obj.sum); // res : 3