簡介
injector是用來做參數自動注入的,例如
function fn ($http, $scope, aService) {}
ng在運行時會把$http, $scope, aService 自動作為參數傳入進行執行。
其實很容易想明白,injector做了兩件事
- 緩衝那些service,以後作為參數注入
- 分析參數列表,找到需要的參數注入
下面源碼分析如何?上面兩件事情。
結構
createInjector -> createInternalInjector return: instanceInjector
所以 createInjector() 返回的是 instanceInjector,結構如下:
{ invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); }}
源碼分析
1. createInjector
function createInjector(modulesToLoad, strictDi) { strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap([], true), // 預先配置$provide,供loadModules中調用註冊service等 providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, // providerInjector, instanceInjector 兩個注入器 // instanceInjector對外提供service等注入,providerInjector對內提供provider擷取 providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); }, strictDi)), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider, undefined, servicename); }, strictDi)); // 載入模組 forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector;}
2. $provide
$provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator}
2.1 supportObject
用於封裝方法,封裝前的方法接受兩個參數 (key, value),經過封裝後的方法能支援傳入object參數,即多個 key -> value。
function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } };}
2.2 provider
回顧下provider、service 和 factory的使用方式
app.factory('serviceName', function(){ return { getName: function(){}, setName: function(){} }});app.service('serviceName', function(){ this.getName = function() {} this.setName = function() {}});app.provider('serviceName', function($httpProvider){ // 注入$httpProvider this.$get = function() { return { getName: function(){}, setName: function(){} }; }});app.provider('serviceName', { $get: function () {}});function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); // 當provider_是fn或者array時可以將其他provider注入到參數 // 因為providerInjector.instantiate(provider_)時可以傳入依賴的其他provider // 這也是provider與service,factory方法不一樣的地方 if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_;}function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]);}function value(name, val) { return factory(name, valueFn(val)); }
最終匯總到provider的實現,將provider緩衝到providerCache,供調用
跟其他不一樣的就是constant的實現,分別儲存到providerCache和instanceCache中,這樣在定義provider還是在定義service是都能注入。
function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value;}
2.3 回顧 loadModules
function runInvokeQueue(queue) { var i, ii; for(i = 0, ii = queue.length; i < ii; i++) { var invokeArgs = queue[i], provider = providerInjector.get(invokeArgs[0]); // 存入queue的如格式[$provide, factory, arguments] // 經過替換,$provide.factory.apply($provide, arguments); // 就是調用$provid的factory,service等 provider[invokeArgs[1]].apply(provider, invokeArgs[2]); }}
2.4 decorator
樣本:
module.config(function($provide) { $provide.decorator('Mail', function($delegate) { $delegate.addCC = function(cc) { this.cc.push(cc); }; return $delegate; });})
使用樣本看出,傳入的參數$delegate是原先的service執行個體,需要在該執行個體上添加方法都可以,即所謂的裝飾器
源碼:
function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { // 通過上面擷取的provider產生需要的service執行個體,再以$delegate注入到參數列表 var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); };}
3. createInternalInjector
3.1 整體結構
// 從cache中擷取,沒有的話調用factory進行建立,具體看getService解析
function createInternalInjector(cache, factory) { function getService(serviceName) { } function invoke(fn, self, locals, serviceName){ } function instantiate(Type, locals, serviceName) { } return { // 執行fn,具有參數注入功能 invoke: invoke, // 執行個體化fn, 可以參數注入 instantiate: instantiate, // 擷取provider或者service get: getService, // 擷取方法的參數列表,供注入使用 annotate: annotate, // 確認是否含有provider或service has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } };}
3.2 annotate
擷取fn的參數列表
// type1function fn (a, b, c) -> ['a', 'b', 'c']// type2['a', 'b', fn] -> ['a', 'b']// type3function fn () {}fn.$inject = ['a', 'c']-> ['a', 'c']
源碼:
function annotate(fn, strictDi, name) { var $inject, fnText, argDecl, last; if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { // strict 模式下或拋錯 if (strictDi) { if (!isString(name) || !name) { name = fn.name || anonFn(fn); } throw $injectorMinErr('strictdi', '{0} is not using explicit annotation and cannot be invoked in strict mode', name); } // 將注釋去掉 fnText = fn.toString().replace(STRIP_COMMENTS, ''); // 將參數全部選出fn(a,b,c,d) -> 'a,b,c,d' argDecl = fnText.match(FN_ARGS); // 分割成array forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject;}
3.3 getService
// 當cache中沒有該service時,進入else, 先cache[serviceName] = INSTANTIATING 做一個標記// 因為接下來調用factory(serviceName),其實是一個遞迴調用// function(servicename) {// var provider = providerInjector.get(servicename + providerSuffix);// return instanceInjector.invoke(provider.$get, provider, undefined, servicename);// }// instanceInjector.invoke(provider.$get 時會將需要注入的參數get出來然後注入// 因此做上標記後就可以判斷是否有循環相依性function getService(serviceName) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } }}
3.4 invoke
function invoke(fn, self, locals, serviceName){ if (typeof locals === 'string') { serviceName = locals; locals = null; } var args = [], // 擷取參數列表 $inject = annotate(fn, strictDi, serviceName), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } // locals優先 args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (isArray(fn)) { fn = fn[length]; } return fn.apply(self, args);}
3.5 instantiate
function instantiate(Type, locals, serviceName) { var Constructor = function() {}, instance, returnedValue; // 當type為array時,擷取最後的參數如:['$window', function($win){}] Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); // 調用invoke執行Type方法 returnedValue = invoke(Type, instance, locals, serviceName); return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;}
instantiate 的作用是用來執行個體化Type的,在執行個體化的過程中可以自動傳入參數到建構函式。