0

I want to add a prototype parameter to JavaScript Object witch returns a sum of other parameters.

Why does this work ?:

function Item() {
    this.a = 2;
    this.b = 3;
    this.c = this.a + this.b;
}

let it = new Item();
console.log(it.c); //5

And this does not ???:

function Item() {
    this.a = 2;
    this.b = 3;
}
Item.prototype.c = this.a + this.b;
console.log(it.c); // Nan

How to access a property so I can do operations in prototypes properties ?

Or need I to always declare it in the constructor of the Object ?

jefi
  • 185
  • 1
  • 13
AlexB
  • 1
  • `this` outside of the constructor doesn't refer to the instance. Log `this` to console in the constructor and after you've defined the prototype property, you'll see the difference. – Teemu Jan 06 '22 at 12:20
  • You need a function. The object doesn't even have `a` and `b` values until it is instantiated. – Quentin Jan 06 '22 at 12:22

0 Answers0