JavaScript inheritance you didn't know

JavaScript inheritance you didn't know

ES6 inheritance

Can inherit static properties

class Car {
  static color = 1;
  constructor(price){
    this.price = price
  }
  test(){
    console.log(this.price)
  }
}

class Cruze extends Car {
  constructor(price){
    super(price)
  }
}

console.log(Cruze.color) //1  

const cruze = new Cruze(3000)
cruze.test(); //3000
 

Print result

ES5 inheritance

'use strict'
function Car(price){
  this.price = price
}

//
Car.color = 'red'
//console.log(new Car(3000))//{price:3000}


//
Car.prototype.test = function(){
  console.log(this.price)
}

function Cruze(price){
  Car.call(this, price) //this window
}
 

Inherit static properties

var staticKeys = Object.entries(Car)
console.log(staticKeys)//[["color", "red"]]//

for(var i =0; i < staticKeys.length;i++){
  var key = staticKeys[i][0]
  var value = staticKeys[i][1]
  Cruze[key] = value
}

console.log(Cruze.color) //red  

 

Inherit the prototype chain

  • Wrong way
Cruze.prototype = Car.prototype //
Cruze.prototype = new Car() //
 
  • Correct but worthless, bad street writing
Cruze.prototype = Object.create(Car.prototype)
Cruze.prototype.constructor = Cruze //constructor
 

Print result:

  • A new generation of writing you don t know
Cruze.prototype = Object.create(Car.prototype, { //contructor
  constructor:{
    value:Cruze,
    writable: false, //
  },
  test:{ //test
    value: function(){
      console.log(this.price)
    }
  }
})
//Cruze.prototype.constructor = {}//  cannot assign to read only property 'constructor' of object '#<Cruze>'

var cruze = new Cruze(3000)
console.log(cruze)
cruze.test()
 

Print result: