Defects of constructor and prototype implementation inheritance
First, let’s analyze the shortcomings of constructor and prototype chain inheritance methods:
The main problem with constructors (object impersonation) is that the constructor method must be used, and methods defined through prototypes cannot be inherited. This is not the best choice. However, if you use the prototype chain, you cannot use the parameterized constructor. How do developers choose? The answer is simple, use both.
Constructor Prototype Mixing Method
This inheritance method uses constructors to define classes instead of using any prototypes. The best way to create a class is to use constructors to define properties and prototypes to define methods. This method also applies to the inheritance mechanism, using objects to pretend to inherit the properties of the constructor, and using the prototype chain to inherit the methods of the prototype object. Rewrite the previous example using these two methods, the code is as follows:
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);
};