Author: Yin weiming
Blog: http://my.donews.com/yinwm/
As I mentioned in the previous article, for JavaScript, a class is a function, and its class methods (that is, static) are all part of this function, and the instance methods, all of them are on 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 a static method 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 as needed.
Function ClassB (){
}
ClassB. staticMethod = ClassA. staticMethod;
ClassB. prototype. prototype = ClassA. prototype;
ClassB. prototype. instanceMethod = function (){
// Method 2
}
For subclasses, a prototype chain is used to inherit the instance methods of methods. This implementation method is selected because the subclass needs to override some of the methods. Prototype is a reference, so writing ClassB. prototype = ClassA. prototype directly will destroy the ClassA instance method while rewriting the ClassB instance method. The modified method shields the parent class.
In the order of searching for methods, instanceA. prototype. method-> ClassA. prototype.
At this time, the inheritance of class methods has been implemented. Now we need to call the parent class method in the subclass.
This is common for Java.
Public void method (){
Super. method ();
}
In JavsScript, a parent reference must be retained to point to ParentClass. prototype.
ClassB. prototype. parent = ClassA. prototype.
In instanceB, call this. parent. method. call (this); to use the method of the parent class. Call is used to upload data to the parent class. I have not thought of a more beautiful solution.
So the complete 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;
}