JavaScript之子类构建工具

时间:2021-09-08 08:32:22
(function(){
var initializing = false;
var superPattern = /xyz/.test(function(){ xyz; }) ? /\b_super\b/ : /.*/; Object.subClass = function(properties){//给Object添加一个subClass方法
var _super = this.prototype;//初始化超类
initailizing = true;
var proto = new this(); for(var name in properties){
proto[name] = typeof properties[name] == "function" && typeof _super[name] == "function" && superPattern.test(properties[name]) ?
(function(name,fn){//定义一个重载函数
return function(){
var tmp = this._super; this._super = _super[name]; var ret = fn.apply(this,arguments);
this._super = tmp;
return ret;
}
})(name,properties[name]) : properties[name];
}
} function Class(){
if(!initializing && this.init){//创建一个仿真类构造器
this.init.apply(this.arguments);
} Class.prototype = proto;//设置类的原型 Class.constructor = Class;//重载构造器引用 Class.subClass = arguments.callee;//让类继续可扩展 return Class;
}
})()