源码如下:
var Class = Object.defineProperties(new Function(), {
extend: {//继承
value: function (mate) {
var child = function () {
this.ctor.apply(this, arguments);
};
for (var a in mate) {
if (typeof mate[a] === "function") {
(function (__name__, __fun__) {
mate[__name__] = function () {
var m = this.__mate__, n = this.__name__;
this.__mate__ = mate, this.__name__ = __name__;
var r = __fun__.apply(this, arguments);
this.__mate__ = m, this.__name__ = n;
return r;
};
})(a, mate[a]);
}
}
mate.__proto__ = this;
child.prototype = mate;
child.extend = Class.extend.bind(mate);
return child;
}
},
_super: {//所有子类的super方法
value: function () {
this.__mate__.__proto__[this.__name__].apply(this, arguments);
}
}
});
Class.prototype = Class.__proto__ = new Object(); //不影响使用,可用于 child instanceof Class
使用方法:
var Parent = Class.extend({
ctor: function (name) {
this._name = name;
},
test: function (data) {
console.log("Parent:", data);
}
});
var Child = Parent.extend({
ctor: function (name) {
this._super(name);
console.log(this._name);
},
test: function () {
this._super(new Date().getTime());
console.log(this instanceof Object, this instanceof Class, this instanceof Parent, this instanceof Child);//true
console.log(this instanceof Parent.extend({ctor: function () {}}), this instanceof Array);//false
}
});
var child = new Child("dfsdf");
child.test();
console.log(Object.getOwnPropertyDescriptors(new Function()));
简介:Class可被无限级继承,任意层级必须包含ctor方法,子对象任何方法内可以通过 this._super() 调用最近的上级父类同名方法
子对象内不可使用 arguments、caller、length、name这几个字段