angularjs源碼筆記(3)--injector

簡介

injector是用來作參數自動注入的,例如javascript

function fn ($http, $scope, aService) {
}

ng在運行時會把$http, $scope, aService 自動做爲參數傳入進行執行。java

其實很容易想明白,injector作了兩件事angularjs

  1. 緩存那些service,之後做爲參數注入
  2. 分析參數列表,找到須要的參數注入

下面源碼分析如何實現上面兩件事情。緩存

結構

createInjector -> createInternalInjector  return: instanceInjector

因此 createInjector() 返回的是 instanceInjector,結構以下:app

{
  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。ide

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的實現,分別保存到providerCacheinstanceCache中,這樣在定義provider仍是在定義service是都能注入。oop

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的參數列表

// type1
function fn (a, b, c) -> ['a', 'b', 'c']

// type2
['a', 'b', fn] -> ['a', 'b']

// type3
function 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) {
        // 嚴格模式下或拋錯
        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的,在實例化的過程當中能夠自動傳入參數到構造函數。

連接

angularjs源碼筆記(1.1)--directive compile

angularjs源碼筆記(1.2)--directive template

angularjs源碼筆記(1.3)--directive ctrl & attrs

angularjs源碼筆記(2)--loader modules

angularjs源碼筆記(3)--injector

angularjs源碼筆記(4)--scope

angularjs源碼筆記(5.1)--$parse

angularjs源碼筆記(5.2)--$parse(未完成)

angularjs源碼筆記(6)--工具類 (未完成)

angularjs源碼筆記(7)--經常使用指令 (未完成)

相關文章
相關標籤/搜索