續:JS動態創建類和實例化

之前寫過一篇文章是 js動態創建類和實例化, 雖然能夠滿足很大部分的需求,但在有些方面還有些欠缺。

正好這段時間在寫HTML5的游戲,需要寫一個只支持HTML5的JS框架,所以把之前的實現方式給完善了下。

創建和實例化方式

(function() {
    var slice = Array.prototype.slice;
    var h5 = function() {
        var cls = function() {
            function T(args) {
                return this.init.apply(this, args);
            }
            var _t = arguments.callee,
                init = _t.prototype.init;
            T.prototype = _t.prototype;
            T.prototype.init = function(){
                var args = arguments;
                if(args.length === 1 && args[0] instanceof _t){
                    return this;
                }
                init && init.apply(this, args);
                return this;
            };
            T.constructor = _t;
            return new T(arguments);
        };
        cls.mix = h5.mix;
        cls.gs = h5.gs;
        h5.mix.apply(cls, arguments);
        return h5.gs.call(cls);
    };
    h5.mix = function(){
        var args = arguments, i = 0, target = this.prototype;
        if(typeof args[0] === 'boolean'){
            i = 1;
            target = this;
        }
        slice.call(args, i).forEach(function(item){
            if(typeof item !== 'object') return;
            for(var pro in item){
                target[pro] = item[pro];
            }
        });
        return this;
    };
    /**
 * getter, setter
     */
    h5.gs = function(){
        var v, name, tp = this.prototype, uname, gname, sname;
        for(name in tp){
            (function(name){
                v = tp[name];
                if(typeof v !== 'function' && name.substr(0, 1) !== '_'){
                    uname = name.substr(0,1).toUpperCase()+name.substr(1);
                    gname = 'get'+uname;
                    sname = 'set'+uname;
                    if(!(gname in tp)){
                        tp[gname]= function(){
                            return this[name];
                        };
                    }
                    if(!(sname in tp)){
                        tp[sname]= function(value){
                            return this[name] = value;
                        };
                    }
                }
            })(name);
        }
        return this;
    };
    this.h5 = h5;

})();


所屬標簽

無標簽

25选5玩法中奖