$inject.instantiate VS $inject.get VS $injector.invoke in angularjs

AngularJS中的$inject.instantiate,$injector.get和$injector.invoke之间有什么区别?
给予以下服务:
app.service('myService',function ($q,$http) {
  return {
    q:    $q,http: $http
  };
});

$injector.get(name,[caller]);

返回所请求服务的实例.

$injector.get('myService');
// { q: $q,http: $http }

$injector.invoke(fn,[self],[localals]);

调用提供的方法,并从$inject中传递给定的参数.

$injector.invoke(function (myService,$http) {
  console.log(myService); // { q: $q,http: $http };
  console.log(this);      // { v: 'im this!' };
  console.log($http);     // null
},{ v: 'im this!' },{ $http: null });

$injector.instantiate(Type,[locals]);

创建给定类型的新实例.使用构造函数,然后使用构造函数注释中指定的参数调用新实例.

假设以下’class’:

function Person (fName,lName,$http,$q) {
  return {
    first_name: fName,last_name:  lName,http: $http,q:    $q
  }
}

现在,如果我们想在我们的控制器中创建一个新的Person,我们可以这样做:

app.controller('...',function ($injector) {
  var $http = $injector.get('$http');
  var $q    = $injector.get('$q');
  var p     = new Person('kasper','lewau',$q);

  console.log(p); // { first_name: 'kasper',last_name: 'lewau',q: $q };
});

想象一下,人有〜20个依赖关系,我们用$inject.get方法获取每个人的每一个.

繁琐!而且 – 你需要保持你的参数&参数同步啊.

相反,你可以这样做:

app.controller('...',function ($injector) {
  var p = $injector.instantiate(Person,{
    fName: 'kasper',lName: 'lewau'
  });
  console.log(p); // { first_name: 'kasper',q: $q };
});

而且 – 如果我们想要,我们可以提供本地的.instantiate调用,以便覆盖内部$inject.get()在实例化时通常会得到的内容.

var p = $injector.instantiate(Person,{
  fName: 'kasper',lName: 'lewau'
},{ $http: 'nothing!',$q: 'nothing!' });
console.log(p); // { first_name: 'kasper',http: 'nothing!',q: 'nothing!' };

我希望解释三者之间的区别.如果您需要更多有关差异的信息,我会推荐这些文章

> http://taoofcode.net/studying-the-angular-injector/
> http://taoofcode.net/studying-the-angular-injector-annotate/
> http://taoofcode.net/studying-the-angular-injector-invoke/
> http://taoofcode.net/studying-the-angular-injector-getservice/
> http://taoofcode.net/studying-the-angular-js-injector-instantiate/

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...