欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angularjs 源码解析之injector

程序员文章站 2022-06-29 08:59:43
简介 injector是用来做参数自动注入的,例如 function fn ($http, $scope, aservice) { } ng在运行时...

简介

injector是用来做参数自动注入的,例如

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

ng在运行时会把$http, $scope, aservice 自动作为参数传入进行执行。

其实很容易想明白,injector做了两件事

  1. 缓存那些service,以后作为参数注入
  2. 分析参数列表,找到需要的参数注入

下面源码分析如何实现上面两件事情。

结构

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的参数列表

// 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的,在实例化的过程中可以自动传入参数到构造函数。