One of the implementation of JavaScript class inheritance
Many JavaScript class inheritance methods have emerged in various blog forums on the Internet. I have browsed some of them, either without comments or without running effects, so I wrote a concise and easy-to-understand version, the accompanying test code is at the bottom.
I accidentally deleted this article, so I made it up again and added an example.
(Function (){
Function. prototype. extend = function (baseClass ){
// This is a function object.
Var oldPrototype = this. prototype, newPrototype = {}, _ super = new baseClass ();
// Inherits all properties and methods.
For (var name in _ super ){
NewPrototype [name] = _ super [name];
}
For (var name in oldPrototype ){
// Only override properties in this new Class.
If (oldPrototype. hasOwnProperty (name )){
// Only function need _ super.
If (typeof oldPrototype [name] = "function" & typeof _ super [name] = "function "){
NewPrototype [name] = (function (name, fn ){
Return function (){
Var tmp = this. _ super;
// Set super method
This. _ super = _ super [name];
Var ret = fn. apply (this, arguments );
This. _ super = tmp;
Return ret;
};
}) (Name, oldPrototype [name]);
}
}
}
This. prototype = newPrototype;
Return this;
};
})();
Var A = function (){
This. hello = function (){
Console. log ("hello, I'm ");
}
};
Var B = function (){};
B. prototype = {
Hello: function (){
This. _ super ();
Console. log ("hello, I'm B ");
}
};
B. extend ();
Var C = function (){};
C. prototype = {
Hello: function (){
This. _ super ();
Console. log ("hello, I'm C ");
}
};
C. extend (B );
Var B = new B ();
Var c = new C ();
// B. hello ();
C. hello ();