SoFunction
Updated on 2025-04-05

An implementation of JavaScript inheritance

Author:Yin Weiming

Blog:/yinwm/

As I mentioned in my previous article, for JavaScript, a class is a function. Its class methods (that is, static) are all part of this function, and instance methods are all on prototype.
function ClassA() {
}

 = function () {
}

 = function () {
}

In my implementation, the inheritance of a class is to copy all class methods of the parent class, so that the subclass has the static methods of the parent class.
Then let the child class point to the prototype of the parent class.
Then you can rewrite some methods according to your needs.
function ClassB() {
}
 = ;
 = ;
 = function () {
// method 2
}

For subclasses, a prototype chain is used to implement the inheritance of the method instance method. This implementation method is chosen because subclasses want to override some of them. And prototype is another reference, so writing directly = will destroy ClassA's instance method while rewriting ClassB's instance method. The modified method will block the parent class.

The order of finding methods is, ->.
At this time, the inheritance of class methods has been implemented, and now it is necessary to implement the method of the parent class in the subclass.
For Java, this is very common
public void method() {
();
}
In JavaScript, in order to implement such functionality, a parent's reference must be kept, pointing to.
 = .
Then call (this); in instanceB, you can use the parent class method. Use call to pass your own data to the parent class. A more beautiful solution, I haven't thought of yet.

So the finished code is
function ClassA() {
}

.method1 = function () {
}

 = function () {
}

function ClassB(){
}

 = ;

 =  = ;

I abstracted this method,

var LCore = function () {
}

 = function (destination, source) {
// copy all functons
for (var prop in source) {
if (prop == “prototype”) {
continue;
}

[prop] = source[prop];
}

// make a reference for parent and reference prototype
 =  = ;

return destination;