Object Inheritance in JavaScript

  • 2021-07-07 06:10:41
  • OfStack

Today, let's look at class inheritance and the mixture of class inheritance and prototype inheritance. The so-called class inheritance is to use call or apply methods to pretend to inherit:


function Desk(size,height){
this.size=size;
this.height=height;
}
function MJDesk(size,height){
Desk.call(this,size,height);// This is called class inheritance .
}
var mj = new MJDesk(10,123);

This is the class inheritance we want to use. With this inheritance, We can access the methods and properties in the class, However, the methods and properties in the parent class prototype cannot be accessed, This method alias pretends to inherit, as the name implies, is a fake inheritance, so of course, fake can't inherit the real prototype, so the shortcomings of class inheritance are also obvious, when we use more, it will cause a waste of memory. Therefore, we have a mixed use of class inheritance and prototype inheritance:


function Desk(size,height){
this.size=size;
this.height=height;
}
function MJDesk(size,height){
Desk.call(this,size,height);// This is called class inheritance .
}
MJDesk.prototype=new Desk();// Prototype inheritance 
var mj = new MJDesk(12,12);
// Of course, the prototype inheritance here uses us 1 Use of chapter talk 1 It is better to inherit empty functions .

Of course, what we use most now is this mixed way!


Related articles: