Class

  • Classes in JS are built on prototypes but also have some syntax and semantics that are unique to classes.

  • Its nature is actually an object with prototypes chain

class Animal {
  constructor(name){
    this._name = name;
  }
  callName(){
    console.log(this._name);
  }
  get name(){
    // not allowed 
    // return this.name;
    return this._name;
  }
  set name(input){
    this._name = input;
  }
}

class Cat extends Animal {
  meow(){
    console.log("meow");
  }
  
}

const mimi = new Cat("mimi");
// inherit from parent
mimi.callName();
// setter
mimi.name = 'mimi1';
// getter
console.log(mimi.name);
  • The contructor can also be have return value, but must be in object format

class Animal {
  constructor(name){
    this._name = name;
    return {test:1}
  }
}

const mimi = new Animal("mimi");
console.log(mimi); // {test : 1 }

Last updated

Was this helpful?