Home >Web Front-end >JS Tutorial >An implementation of JavaScript inheritance_javascript skills
Author: Yin Weiming
Blog: http://my.donews.com/yinwm/
As I said in my previous article, for JavaScript, a class is a function, and its class Methods (that is, static) are all part of this function, and instance methods are all on the prototype.
function ClassA() {
}
ClassA.staticMethod = function () {
}
ClassA.prototype.instanceMethod = function () {
}
In my implementation, the inheritance of a class is to copy all the class methods of the parent class, so that the subclass has the static methods of the parent class.
Then let the prototype.prototype of the subclass point to the prototype of the parent class.
You can then rewrite some methods according to your own needs.
function ClassB() {
}
ClassB.staticMethod = ClassA.staticMethod;
ClassB.prototype.prototype = ClassA.prototype;
ClassB.prototype.instanceMethod = function () {
// method 2
}
For subclasses, use a prototype chain to implement inheritance of method instance methods. The reason for choosing this implementation method is that subclasses need to override some of the methods. And prototype is a reference, so directly writing ClassB.prototype = ClassA.prototype will destroy the instance method of ClassA while rewriting the instance method of ClassB. The modified method will block the parent class.
The order of finding methods is, instanceA.prototype.method -> ClassA.prototype.
At this time, the inheritance of class methods has been implemented. Now it needs to be implemented in the subclass to call the method of the parent class. .
For Java, such use is very common
public void method() {
super.method();
}
In JavsScript, in order to implement such functions, it must Keep a parent reference pointing to ParentClass.prototype.
ClassB.prototype.parent = ClassA.prototype.
Then call this.parent.method.call(this); in instanceB to use the method of the parent class . Use call to transfer your data to the parent class. There's a prettier solution I haven't thought of yet.
So the completed code is
function ClassA() {
}
ClassA.prototype.method1 = function () {
}
ClassA .staticMethod = function () {
}
function ClassB(){
}
ClassB.staticMethod = ClassA.staticMethod;
ClassB.prototype. prototype = ClassB.prototype.parent = ClassA.prototype;
I abstracted an extend method,
var LCore = function () {
}
LCore .extend = function (destination, source) {
// copy all functons
for (var prop in source) {
if (prop == “prototype”) {
continue;
}
destination.prototype[prop] = source[prop];
}
// make a reference for parent and reference prototype
destination.prototype.prototype = destination. prototype.parent = source.prototype;
return destination;
}