SpeakingJavascriptOfClass inheritanceThe prototype chain is inevitable, but the inheritance implemented only through the prototype chain has many defects.
No parameter class inheritance issues
Let's take A look at the sample code to implement B inherited from:
- 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 question of this Code is:
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:
- 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″);
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:
- 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:
- 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 is naturally overloaded), so it cannot be overwritten:
- For (var m in A. prototype)
- {
- If (! B. prototype [m])
- {// The parent class cannot override the subclass method.
- B. prototype [m] = A. prototype [m];
- }
- }