Home  >  Article  >  Web Front-end  >  Another discussion on Javascript class inheritance_javascript skills

Another discussion on Javascript class inheritance_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:09:471136browse

The problem of parameterless class inheritance

First look at a sample code to implement B inheritance from A:

Copy code The code 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 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:
Copy code 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 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. :
Copy code The code is as follows:

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:
Copy code 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 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:
Copy code The code is as follows:

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn