Speaking of Javascript's class inheritance, it is inevitable that the prototype chain cannot be separated, but inheritance only through the prototype chain has many shortcomings.
Problem of inheritance of no parameters
Let’s first look at a piece of sample code to implement B inheritance from A:
The code copy is 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 problems with this code are:
1. A needs to be instantiated as B's prototype, and A's constructor is executed at this time. However, according to object-oriented rules, B and its parent class A should not be executed before instantiating B.
2. Changed the prototype of B, resulting in b.constructor not B but A.
There is a problem with ginseng class inheritance
Suppose A and B have two string parameters s1 and s2. A calculates the total length of the two strings, and B directly calls A with s1 and s2 as parameters:
The code copy is 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 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:
The code copy is as follows:
s1 is undefined
Solution
The scope of s1 and s2 is only in B. To pass them to A, you can only operate in B. It can be achieved by using the function's apply method:
The code copy is as follows:
function B(s1, s2) {
A. apply(this, arguments);
alert(this.totalLength);
}
The next question is how to add method A to the prototype B. This is not difficult, just go through A.prototype and copy the method to B.prototype. It should be noted that for methods with the same name, subclasses are naturally preferred (overloaded), so they cannot be overridden:
The code copy is as follows:
for (var m in A.prototype) {
if (!B.prototype[m]) { // Methods of parent class cannot override subclasses
B.prototype[m] = A.prototype[m];
}
}
postscript
Considering that high-level languages such as C# and Java have abandoned multiple inheritance, the situation of single inheritance is discussed in this article. The inheritance method described in this article will also be written as an extension of jRaiser and will be released later.