Inheritance in ES5 (combinatorial inheritance)

  ES6 class inheritance uses the extends keyword, so how is it implemented in ES5?

  ES5 uses a combination of constructor and prototype object to simulate inheritance, so it is also called combined inheritance;

  The core principle: borrow the parent constructor through call (), and point this of the parent type to this of the subtype;

  This inheritance is actually calling the parent constructor in the child constructor when the child constructor is called to create the instance object, then you can get the members of the parent constructor, and modify the this of the called parent constructor Just point to a sub-function, the member will be inherited into the sub-function;

  In a word: use call () to call the parent constructor in the child constructor to achieve inheritance; remember to modify this in the parent constructor to this in the child function

function Father(uname, age){
  this.uname = uame;
  this.age = age;        
}
function Son(uname, age){
  Father.call(this);
}

  Borrow prototype object inheritance method

Son.prototype = new father (); // Because the method in the prototype object of Father can be accessed through the prototype chain 
Son.prototype.constructor = Son; // The assignment operation above will make the constructor of Son point to Father

  

Guess you like

Origin www.cnblogs.com/joeynkay/p/12734884.html