Home > OS >  why constructor properties is not inherited to instance of it
why constructor properties is not inherited to instance of it

Time:09-12

class Person {
   constructor() {
    let name = 'John';
  }
  talk() {
    return "talking"
 }
}
const me = new Person();
Person.prototype.walk = function walk() { return "walking"; };

as you can see in the image below, why I am getting undefined for me.name (although it was present in the constructor)?

Why accessible through Person and why not with me?

Do we get only the prototype object properties to be accessed to me, or do we get constructor properties? If not then what's the use of passing them by default to the me instance as you can see in the image below?

enter image description here

CodePudding user response:

MDN docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Does not how JavaScript classes work.
You should check the docs.
To define the constructor you have to define the constructor function inside the class, which is named constructor.

class Person {

  constructor(name = 'John') {
    this.name = name
  }

  talk() {
    return 'talking'
  }

}

CodePudding user response:

let declares a local variable (one which disappears when the } bracket is closed). You need to store your variable as part of the class.

From the MDN example:

class Polygon {
  constructor(height, width) {
    this.area = height * width;
  }
}

console.log(new Polygon(4, 3).area);
// expected output: 12
  • Related