用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

javascript 反射与依赖注入

2015-05-30 作者: dandan举报

[java]代码库

var service = function() {  
    return { name: 'Service' };  
}  
var router = function() {  
    return { name: 'Router' };  
}  

var doSomething = function(other) {  
    var s = service();  
    var r = router();  
};  

var doSomething = injector.resolve('router,,service', function(a, b, c) {  
    expect(a().name).to.be('Router');  
    expect(b).to.be('Other');  
    expect(c().name).to.be('Service');  
});  
doSomething("Other");  
带参数
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);  
            }  
        }  
    };  

injector.resolve(['service,,router', function(service, router) {  
  
}]);  


因为不在需要传递参数,直接可以从作用域中访问到。


var injector = {  
   dependencies: {},  
   register: function(key, value) {  
       this.dependencies[key] = value;  
   },  
   resolve: function(deps, func, scope) {  
       var args = [];  
       scope = scope || {};  
       for(var i=0; i<deps.length, d=deps[i]; i++) {  
           if(this.dependencies[d]) {  
               scope[d] = this.dependencies[d];  
           } else {  
               throw new Error('Can\'t resolve ' + d);  
           }  
       }  
       return function() {  
           func.apply(scope || {}, Array.prototype.slice.call(arguments, 0));  
       }          
   }  

var doSomething = injector.resolve(['service', 'router'], function(other) {  
    expect(this.service().name).to.be('Service');  
    expect(this.router().name).to.be('Router');  
    expect(other).to.be('Other');  
});  
doSomething("Other");  


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...