Common Inheritance in js Combined Inheritance

  • 2021-07-26 06:45:47
  • OfStack

Combinatorial inheritance is sometimes called pseudo-classical inheritance, which refers to an inheritance mode that combines prototype chain and borrowing constructor technology into one block, so as to give full play to the strengths of the two. The idea behind it is to use prototype chain to inherit prototype attributes and methods, while borrowing constructor to inherit instance attributes. This not only realizes function reuse by defining methods on the prototype, but also ensures that each instance has its own attributes.


 function SuperType(name){
  this.name=name;
  this.colors=["red","blue","green"];
 }
 SuperType.prototype.sayName=function(){
  console.log(this.name);
 }
 function SubType(name,age){
  SuperType.call(this,name);
  this.age=age;
 }
 SubType.prototype=new SuperType();
 SubType.prototype.constructor=SubType;
 SubType.prototype.sayAge=function(){
  console.log(this.age);
 }
 var instance1=new SubType("zxf",24);
 instance1.colors.push("black");
 console.log(instance1.colors);//["red","blue","green","black"]
 instance1.sayName();//"zxf"
 instance1.sayAge();//24
 var instance2=new SubType("jay",36);
 console.log(instance2.colors);//["red","blue","green"]
 instance2.sayName();//"jay"
 instance2.sayAge();//36

In this example, the supertype constructor defines two properties, name and colors. The prototype of supertype defines a method, sayname (). The subtype constructor calls supertype passing in the name parameter, followed by defining its own property age. The instance of supertype is then assigned to the prototype of subtype, and then the method sayage () is defined on the new prototype. In this way, two different instances of subtype can both have attributes, including colors attributes, and use the same method.

The disadvantage of combined inheritance is that the supertype constructor is called twice, once when the prototype of subtype is assigned, and once when the subclass is instantiated, call is called, which masks two attributes with the same name in the prototype.

Reference Book: Javascript Advanced Programming (3rd Edition);


Related articles: