How to solve the problem of no parameters and parameter class inheritance in Javascript
This article describes how to solve the problem of No-parameter and parameter-class inheritance in Javascript. This article explains the problem of non-parameter class inheritance and the problem of parameter-class inheritance, and provides a solution, for more information, see
When it comes to Javascript class inheritance, prototype chain is inevitable, but inheritance implemented only through prototype chain has many defects.
No parameter class inheritance issues
Let's take A look at the sample code to implement B inherited from:
The Code is as follows:
Function (){
}
A. prototype. a1 = function (){};
Function B (){
}
B. prototype = new ();
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. You need to instantiate A as the prototype of B and then execute the constructor of. However, according to the object-oriented rules, the constructor of B and its parent class A should not be executed before B is instantiated.
2. Changed prototype of B, resulting in B. constructor not B but.
Questions about inheritance of parameters
Assume that A and B both have two string parameters s1 and s2. A calculates the total length of the two strings. B calls A directly with s1 and s2 as the parameters:
The Code is as follows:
Function A (s1, s2 ){
This. totalLength = s1.length + s2.length;
}
A. prototype. a1 = function (){
};
Function B (s1, s2 ){
}
B. prototype = new ();
B. prototype. b1 = function (){
};
New B ("AB", "123 ");
We can see that there is no way to upload s1 and s2 to A in this Code, but there is no parameter when instantiating A as A prototype of B, so an exception occurs:
The Code is as follows:
S1 is undefined
Solution
The s1 and s2 scopes are only within B. to pass them to A, they can only be operated in B. This can be achieved through the apply method of the function:
The Code is as follows:
Function B (s1, s2 ){
A. apply (this, arguments );
Alert (this. totalLength );
}
The next question is how to add the method 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, the subclass takes precedence over (overload), and therefore cannot overwrite:
The Code is as follows:
For (var m in A. prototype ){
If (! B. prototype [m]) {// The parent class cannot overwrite the subclass method.
B. prototype [m] = A. prototype [m];
}
}
Postscript
Considering that C #, Java and other advanced languages all discard multi-inheritance, this article only discusses the single inheritance situation. The inheritance method described in this article will also be written as an extension of jRaiser, which will be released later.