2

I'm creating two ES js Classes (Person, Teacher)

class Person {
    constructor (name = "no name") {
    this.name = name
}

Teacher inherit from Person

class Teacher extends Person {      
    constructor(name, degree){
        super(name)
            this.degree = degree; 
    }
}

In the teacher constructor, I have a new property called degree.

when I create a new property called Full name that takes name and degree. Degree shows as undefined. Although when I log object teacher property is there. It looks like a delay issue. But, shouldn't I be able to access property right away?

class Person {
  constructor(name = 'no name') {
    this.name = name;
  }
}

class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
  }

  fullname = this.degree + this.name;
  printFullName() {
    console.log(this.fullname);
  }
}

let person = new Teacher('Adam', 'MS.');

console.log(person);

person.printFullName(); // undefined Adam

https://repl.it/@adbarani/TrimBrilliantPaintprogram#index.js

trincot
  • 317,000
  • 35
  • 244
  • 286
Adam Bahrani
  • 65
  • 3
  • 11

2 Answers2

1

This is the behaviour specified in the MDN documentation:

Public instance fields are added with Object.defineProperty() either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass.

Your code example is in the second case. The order of execution is thus:

  1. Execute super() in case your class is a subclass
  2. Define the public instance fields on this
  3. Execute the rest of the constructor

If you need a work around, then don't define fullname with the field syntax, but assign to this.fullname as part of the constructor function.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

Update fullname to a getter to compute the property value when it is accessed:

class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
  }

  get fullname() {
    return this.degree + this.name;
  };

  printFullName() {
    console.log(this.fullname);
  }
}

It sounds like you want fullname to be a property, why not set it in the constructor then?

class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
    this.fullname = this.degree + this.name;
  }

  printFullName() {
    console.log(this.fullname);
  }
}

Otherwise just change printFullName to do the work for you:

  printFullName() {
    console.log(this.degree + this.nam);
  }

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91