constructors, prototypes implementation defects of inheritance
First, we analyze the two kinds of defects in the constructor and prototype chain to implement the inheritance method:
The main problem with constructors (object impersonation) is that you must use the constructor method and you cannot inherit the methods defined by the stereotype, which is not the best choice. However, if you use a prototype chain, you cannot use a constructor with parameters. How do developers choose? The answer is simple, both are used.
Constructor + prototype Blending method
This inheritance uses constructors to define classes, not using any prototypes. The best way to create a class is to define the property with a constructor and define the method with the stereotype. This approach also applies to inheritance mechanisms, using objects to impersonate inherited constructor properties, and using a prototype chain to inherit prototype objects. Rewrite the previous example in both ways, with the following code:
Copy Code code 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 first line of highlighted code, in the ClassB constructor, an object is used to impersonate an inherited ClassA class's Scolor property. In the second line of highlighted code, the method of inheriting the ClassA class with a prototype chain. The instanceof operator still works correctly because the prototype chain is used in this blending mode.
The following example tests this code:
Copy Code code 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"