Constructor and prototype inheritance Defects
First, we will analyze the defects of the constructor and prototype chain inheritance methods:
The main problem with Constructors (Object impersonating) is that they must use the constructor method and cannot inherit the methods defined through the prototype. This is not the best choice. However, if the prototype chain is used, the constructor with parameters cannot be used. How do Developers choose? The answer is simple. Both are used.
Constructor + prototype hybrid mode
This inheritance method uses constructors to define classes, rather than any prototype. The best way to create a class is to use the constructor to define attributes and the prototype to define attributes. This method also applies to the Inheritance Mechanism. It uses an object to impersonate the attributes of the inherited constructor and uses the prototype object method of the prototype chain. Use these two methods to rewrite the previous example. The Code is as follows:
Copy codeThe Code is as follows: function ClassA (sColor ){
This. color = sColor;
}
ClassA. prototype. sayColor = function (){
Alert (this. color );
};
Function ClassB (sColor, sName ){
ClassA. call (this, sColor );
This. name = sName;
}
ClassB. prototype = new ClassA ();
ClassB. prototype. sayName = function (){
Alert (this. name );
};
In this example, the inheritance mechanism is implemented by two lines of highlighted blue code. In the Code highlighted in the first line, in the ClassB constructor, The sColor attribute of the ClassA class is inherited by impersonating an object. In the highlighted code in the second line, use the prototype chain to inherit the ClassA class method. Because this hybrid method uses the prototype chain, the instanceof operator can still run correctly.
The following example tests the Code:
Copy codeThe Code is as follows: var objA = new ClassA ("blue ");
Var objB = new ClassB ("red", "John ");
ObjA. sayColor (); // output "blue"
ObjB. sayColor (); // output "red"
ObjB. sayName (); // output "John"