网上各博客论坛出现了很多JavaScript的类继承方法,浏览了一些,不是没注释,就是没有运行效果,于是自己写了个简洁易懂的版本,附带测试代码在最下面。
刚不小心删除了该文章,因此重新补上,另外加强了示例。
(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 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();