Home > Software design >  JavaScript Class properties inside constructor
JavaScript Class properties inside constructor

Time:12-09

Defined one property outside the constructor like name, and one inside like this.id, but when i initialized, I got property, which was outside the constructor.

I created one class person and defined a property name (not in constructor) like this

class Person {
  name;
}

let instance_ = new Person()
console.log(instance_)

I got output

Person {name: undefined}

Then, I defined other class Employee and defined a property id (in constructor)

class Employee {
  constructor() {
    this.id
  }
}

let instanceEmp_ = new Employee()
console.log(instanceEmp)

The output I got

Employee {} //Didn't get id property

I didn't get id property in class Employee. Why?

CodePudding user response:

You have to assign something into that property, otherwise js thinks it's a getter

class Employee {
  constructor() {
    this.id = undefined
  }
}

let instanceEmp = new Employee()
console.log(instanceEmp)

CodePudding user response:

One solution is to pass an id variable to the constructor:

class Employee {
   constructor(id) {
      this.id = id;
   }
}

let instanceEmp = new Employee()
console.log(instanceEmp) // Employee {id: undefined}
  • Related