JavaScript 依赖注入的两种写法

第一种,模块注入需要两次,两次的顺序要固定,模块名能在调用时改名
var injector = {
    dependencies: {},
    register: function(key, value) {
        this.dependencies[key] = value;
    },
    resolve: function(deps, func, scope) {
        var args = [];
        for(var i=0; i<deps.length, d=deps[i]; i++) {
            if(this.dependencies[d]) {
                args.push(this.dependencies[d]);
    } else {
    throw new Error('Can\'t resolve ' + d);
            }
        }
        return function() {
            func.apply(scope || {}, args.concat(Array.prototype.slice.call(arguments, 0)));
        }
    }
}
第二种,模块注入只需一次,不需要固定顺序,但是模块名不能修改
var injector = {
    dependencies: {},
    register: function(key, value) {
        this.dependencies[key] = value;
    },
    resolve: function() {
        var func, deps, scope, args = [], self = this;
        if(typeof arguments[0] === 'string') {
            func = arguments[1];
            deps = arguments[0].replace(/ /g, '').split(',');
            scope = arguments[2] || {};
        } else {
            func = arguments[0];
            deps = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].replace(/ /g, '').split(',');
            scope = arguments[1] || {};
        }
        return function() {
            var a = Array.prototype.slice.call(arguments, 0);
            for(var i=0; i<deps.length; i++) {
                var d = deps[i];
                args.push(self.dependencies[d] && d != '' ? self.dependencies[d] : a.shift());
            }
            func.apply(scope || {}, args);
        }        
    }
}

猜你喜欢

转载自blog.csdn.net/amesteur/article/details/80272008