There are several ways to inherit JavaScript inheritance, and now it's a combination of them.
Combinatorial inheritance is a combination of the prototype chain and the use of the construction function of the two methods of inheritance, respectively, using their strengths, to avoid the shortcomings. Let's talk about these two technologies first.
Prototype chain
The prototype chain is the chain between the instance and the prototype.
Sub-type constructors And Super type constructors There is no association between them, simply Sub-type constructors the prototypeAsexamples of super-type constructors。 Suchinstance of a subtype constructorYou can sharea method of super-type constructor prototypeAndproperties of a super-type constructor。
Such as:
var new supertype ();
The disadvantage of the prototype chain is that when Subtype.prototype as an instance, the attribute in the supertype constructor, when it is a prototype of subtype , These properties are shared by instances of the subtype as the properties of the prototype, and because there is no association between the constructors of the two types, when you create an instance of subtype , you cannot go to supertype The constructor passes the parameters.
borrowing Constructors
in the in the sub-type constructor called Super Type Constructors , use the call () or the apply () method.
Such as:
Supertype.call (this); or Supertype.call (this, parameter);
By doing so, the properties in the supertype constructor are called as specific, i.e., subtype instances, and these properties are unique to each instance, not to the shared one. You can also pass parameters to the supertype constructor.
However, the method defined in the supertype.prototype is not visible to subtype .
Both of these methods have their own strengths and are short. So combine them together, and there's a combination of inheritance. Understanding the prototype chain and borrowing the constructor is not difficult to understand the combination of inheritance.
Combining Inheritance
Composite Inheritance is a method of inheriting a prototype through a prototype chain , inheriting properties by borrowing a constructor function . This allows the property to be inherited separately from the method, which is shared by all instances, and attributes are specific to each instance.
Of course, the combination of inheritance also has its disadvantage, that is, the properties of the super-type are inherited two times, one is a subtype prototype inheritance, and the other is a subtype instance inheritance, but the instance inherits properties that mask the properties of the stereotype inheritance.
JavaScript combination Inheritance