Implementation principle: Define a wrapper function extend; the function has 2 parameters, the child represents the subclass, and the parent represents the parents, and within the function, an empty function f is defined to implement the function relay, the prototype of F is set to the prototype of the parent class, and then the instance of the empty function is passed to the prototype of the subclass. Benefits of using an empty function: avoiding direct instantiation of the parent class can introduce system performance problems, such as a large instance of the parent class, which consumes a lot of memory;
function Extend (child,parent) {
//child represents a subclass, and parent represents a child class
//define an empty function first
var F = function () {};
//Set the prototype of the empty function as the prototype of the parent class
F.prototype = Parent.prototype;
//Instantiate an empty function and pass the parent prototype reference to the subclass
Child.prototype = new F ();
//Resets the constructor of the subclass prototype to the subclass itself
Child.prototype.constructor = child;
//Save the prototype of the parent class in the subclass to avoid coupling the child class to the parent class
Child.parent = Parent.prototype;
if (Parent.prototype.constructor!== Parent) {
//To detect if the constructor of the parent prototype is the prototype itself
Parent.prototype.constructor = Parent;
}
}
The test code is as follows:
Below we define 2 classes A and B, we aim to implement B inheriting from a
function A (x) {
this.x = x;
This.getx = function () {
return this.x;
}
}
A.prototype.add = function () {
return this.x + this.x;
}
A.prototype.mul = function () {
return this.x * this.x;
}
Constructor b
function B (x) {
A.call (THIS,X); //Inherit all properties and methods in constructor a
}
Extend (b,a); //b inherits from a
var B = new B (10);
Console.log (B.getx ()); 10
Console.log (B.add ()); 20
Console.log (B.mul ()); 100
JS wrapper class for prototype inheritance