ÎÒÃÇÑ»·±éÀúdependenciesÊý×飬Èç¹û·¢ÏÖȱʧÏîÔò³¢ÊÔ´Óarguments¶ÔÏóÖлñÈ¡¡£Ð»ÌìлµØ£¬µ±Êý×éΪ¿Õʱ£¬shift·½·¨Ö»ÊÇ·µ»Øundefined£¬¶ø²»ÊÇÅ׳öÒ»¸ö´íÎó£¨ÕâµÃÒæÓÚwebµÄ˼Ï룩¡£Ð°æµÄinjectorÄÜÏñÏÂÃæÕâÑùʹÓãº
var doSomething = injector.resolve(function(service, other, router) {
console.log(service().name); //Service
console.log(router().name); //Router
console.log(other().name); //Other
});
doSomething(other);
²»±ØÖØдÒÀÀµ²¢ÇÒËûÃǵÄ˳Ðò¿ÉÒÔ´òÂÒ¡£ËüÈÔÈ»ÓÐЧ£¬ÎÒÃdzɹ¦¸´ÖÆÁËAngularµÄħ·¨¡£
È»¶ø£¬ÕâÖÖ×ö·¨²¢²»ÍêÃÀ£¬Õâ¾ÍÊÇ·´ÉäÀàÐÍ×¢ÉäÒ»¸ö·Ç³£´óµÄÎÊÌ⡣ѹËõ»áÆÆ»µÎÒÃǵÄÂß¼£¬ÒòΪËü¸Ä±ä²ÎÊýµÄÃû×Ö£¬ÎÒÃǽ«ÎÞ·¨±£³ÖÕýÈ·µÄÓ³Éä¹Øϵ¡£ÀýÈ磬doSometing()ѹËõºó¿ÉÄÜ¿´ÆðÀ´ÏñÕâÑù£º
var doSomething=function(e,t,n){var r=e();var i=t()}
AngularÍŶÓÌá³öµÄ½â¾ö·½°¸¿´ÆðÀ´Ïñ£º
var doSomething = injector.resolve(['service', 'router', function(service, router) {
}]);
Õâ¿´ÆðÀ´ºÜÏñÎÒÃÇ¿ªÊ¼Ê±µÄ½â¾ö·½°¸¡£ÎÒûÄÜÕÒµ½Ò»¸ö¸üºÃµÄ½â¾ö·½°¸£¬ËùÒÔ¾ö¶¨½áºÏÕâÁ½ÖÖ·½·¨¡£ÏÂÃæÊÇinjectorµÄ×îÖÕ°æ±¾¡£
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);
}
}
}
resolve·Ã¿Í½ÓÊÜÁ½»òÈý¸ö²ÎÊý£¬Èç¹ûÓÐÁ½¸ö²ÎÊýËüʵ¼ÊÉϺÍÎÄÕÂÇ°ÃæдµÄÒ»Ñù¡£È»¶ø£¬Èç¹ûÓÐÈý¸ö²ÎÊý£¬Ëü»á½«µÚÒ»¸ö²ÎÊýת»»²¢Ìî³ädepsÊý×飬ÏÂÃæÊÇÒ»¸ö²âÊÔÀý×Ó£º
var doSomething = injector.resolve('router,,service', function(a, b, c) {
console.log(a().name); //Service
console.log(c().name); //Router
console.log(b().name); //Other
});
doSomething(other);
Äã¿ÉÄÜ×¢Òâµ½ÔÚµÚÒ»¸ö²ÎÊýºóÃæÓÐÁ½¸ö¶ººÅ——×¢ÒâÕâ²»ÊDZÊÎ󡣿Õֵʵ¼ÊÉÏ´ú±íother²ÎÊý£¨Õ¼Î»·û£©¡£ÕâÏÔʾÁËÎÒÃÇÊÇÈçºÎ¿ØÖƲÎÊý˳ÐòµÄ¡£
Ö±½Ó×¢ÈëScope
ÓÐʱÎÒ»áÓõ½µÚÈý¸ö×¢Èë±äÁ¿£¬ËüÉæ¼°µ½²Ù×÷º¯ÊýµÄ×÷ÓÃÓò£¨»»¾ä»°Ëµ£¬¾ÍÊÇthis¶ÔÏ󣩡£ËùÒÔ£¬ºÜ¶àʱºò²»ÐèҪʹÓÃÕâ¸ö±äÁ¿¡£
¡¡