JavaScript之子类构建工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(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;      
    }  
})()

 

posted @   千千寰宇  阅读(144)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示