When it comes to the class inheritance of JavaScript, the prototype chain is inevitable, but the inheritance through the prototype chain has many defects.
Problems with no parameter class inheritance
Let's take a look at a sample code to realize B inherits from a:
Copy Code code as follows:
function A () {
}
a.prototype.a1 = function () {};
function B () {
}
B.prototype = new A ();
B.PROTOTYPE.B1 = function () {};
var B = new B ();
Alert (B.constructor = = A); True
Alert (B.constructor = = b); False
The main problem with this code is:
1. The prototype of a as B needs to be instantiated, and a constructor is executed at this time. However, before instantiating B, the constructors of B and its parent class A should not be executed, according to object-oriented rules.
2. Changed the prototype of B, resulting in b.constructor not B but a.
Problems with argument class inheritance
Suppose A and B have two string arguments S1 and s2,a calculate the total length of the two-segment string, b directly call a on S1, S2 for arguments:
Copy Code code as follows:
function A (s1, S2) {
This.totallength = S1.length + s2.length;
}
a.prototype.a1 = function () {
};
function B (s1, S2) {
}
B.prototype = new A ();
B.PROTOTYPE.B1 = function () {
};
New B ("AB", "123");
As you can see, there is no way to upload S1 and S2 to a in this code, and there is an exception because there are no arguments for instantiating a as a prototype of B:
Copy Code code as follows:
Solution
The scope of S1 and S2 is only within B, and to pass them to a, you can only operate in B, using the application method of the function:
Copy Code code as follows:
function B (s1, S2) {
A.apply (this, arguments);
alert (this.totallength);
}
The next question is how to add the method of a to the prototype of B. This is not difficult, as long as the traversal A.prototype, the method copy to B.prototype can be. Note that for a method of the same name, nature is a subclass priority (overload) and cannot be overridden:
Copy Code code as follows:
For (var m in A.prototype) {
if (! B.prototype[m]) {//Parent class cannot overwrite method of subclass
B.PROTOTYPE[M] = a.prototype[m];
}
}
PostScript
In view of C #, Java and other high-level languages have abandoned multiple inheritance, so this article is also discussed in the case of single inheritance. The inheritance method described in this article will also be written as an extension of Jraiser, later published.