续:JS动态创建类和实例化

2298次阅读  |  发布于5年以前

之前写过一篇文章是 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;

})();

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8