Online blog Forum appeared a lot of JavaScript class inheritance methods, browse some, not without comments, is not running effect, so I wrote a simple and understandable version, with the test code at the bottom.
The article has just been accidentally deleted, so it is re-made, and the example is strengthened.
(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 the 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 A");
}
};
var B = function () {};
B.prototype = {
Hello:function () {
This._super ();
Console.log ("Hello, I ' m B");
}
};
B.extend (A);
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 ();
One of the JavaScript class inheritance implementations