The problem of parameterless class inheritance
First look at a sample code to implement B inheritance from A:
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:
* A needs to be instantiated as the prototype of B. At this time, the constructor of A is executed. But according to object-oriented rules, before instantiating B, the constructors of B and its parent class A should not be executed.
* Changed the prototype of B, resulting in b.constructor not being B but A.
There is a problem with parameter class inheritance
Assume that A and B both have two string parameters s1 and s2. A calculates the total length of the two strings, and B directly uses s1, s2 calls A as parameter:
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 pass s1 and s2 to A in this code, and because there are no parameters when instantiating A as the prototype of B, an exception occurs. :
s1 is undefined
Solution
The scope of s1 and s2 is only in B. To transfer them to A, you can only operate in B. This can be achieved with the help of the apply method of the function:
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, just traverse A.prototype and copy the method to B.prototype. It should be noted that for methods with the same name, subclasses take priority (overloading), so they cannot be overridden:
for (var m in A.prototype) {
if (!B.prototype[m]) { // The parent class cannot override the method of the subclass
B .prototype[m] = A.prototype[m];
}
}
Postscript
Considering that high-level languages such as C# and Java have abandoned multiple inheritance , therefore, this article discusses only the case of single inheritance. The inheritance method described in this article will also be written as an extension of jRaiser and will be released later.