Home >Web Front-end >JS Tutorial >Javascript parameterless and parameterized class inheritance problem solutions_javascript skills
When it comes to Javascript class inheritance, it must be inseparable from the prototype chain, but inheritance implemented only through the prototype chain has many flaws.
Problems with parameterless class inheritance
Let’s first look at a sample code to implement B inheriting from A:
function B() {
}
B.prototype = new A();
B.prototype.b1 = function() { };
var b = new B();
alert(b.constructor == A); // true
alert(b.constructor == B); // false
1. 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.
2. Changed the prototype of B, resulting in b.constructor not being B but A.
There is a problem with parameter class inheritance
Suppose both A and B have two string parameters s1 and s2. A calculates the total length of the two strings. B directly calls A with s1 and s2 as parameters:
function B(s1, s2) {
}
B.prototype = new A();
B.prototype.b1 = function() {
};
new B("ab", "123");
The scope of s1 and s2 is only in B. If you want 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:
Considering that high-level languages such as C# and Java have abandoned multiple inheritance, this article only discusses single inheritance. The inheritance method described in this article will also be written as an extension of jRaiser and will be released later.