如何在 AngularJS 中将依赖项传递给原型函数

How to pass dependencies to prototype functions in AngularJS

有没有更简洁的方法来访问原型函数中的依赖项(即构造函数参数)?特别是 AngularJS Services.

我只知道

function SomeSrvc($http, ...other deps...) {
  var srvc = this;

  // Verbose way of storing dependencies
  srvc.$http = $http;
  srvc.dep2 = dep2;
  srvc.dep3 = dep3;
  srvc.dep4 = dep4;
}

SomeSrvc.prototype.doSomething = function() {
  var srvc = this;
  // Do stuff with srvc.$http and other srvc.deps...
};

这实际上是documentation

中描述的官方方式
function SomeClass(greeter) {
  this.greeter = greeter;
}

SomeClass.prototype.doSomething = function(name) {
  this.greeter.greet(name);
}

但我会考虑改用 ES2015 类 语法。

export default class SomeClass {
  constructor(greeter) {
    this._greeter = greeter;
  }

  doSomething() {
    this._greeter.greet(name);
  }
}

您可以阅读更多内容here

我知道的最短的方法是避免在外部作用域中使用原型并简单地使用闭包:

function SomeSrvc($http, ...other deps...) {
  var srvc = this;

  srvc.doSomething = function() {
    // just use $http without this / srvc
  };
}

简短而优美。如果你真的喜欢类似原型的语法,只需调整缩进(但在我看来这会更难看):

function SomeSrvc($http, ...other deps...) {
  var srvc = this;



srvc.doSomething = function() {
  // Do stuff with srvc.$http and other srvc.deps...
};

}

这会产生相同的效果 - 使用 new 运算符创建的对象将具有此功能,并且 angular 服务将以这种方式创建。

另外,这种方式有一个很好的副作用。它不会在服务对象上创建变量,因此可以将它们视为 private,当将所有变量分配给服务时使它们 public 并且可以从另一个 angular 模块访问。目前,只需注入您的服务,您就可以通过调用例如

来使用所有注入的模块
SomeSrvc.$http

这完全违背了依赖注入的整个理念。

对于服务,而不是控制器,我做了一些不同的事情

module.factory('myService', function(dep1, dep2){
    var createInternal=function(){ 
        var internal = Object.create(proto);
        internal.init( ... ); 
        return internal;
    };
    var service = function(){ 
        var internal = createInternal(); 
        return { 
            doSomething: function(a, b, c){ return internal.doSomething(a,b,c); },
            ...
        };
    };
    var proto = { 
        init: function( ... ){ 
                  dep1.greet();
                  dep2.doSomethingElse(); 
                  ... 
              },
        doSomething: function(a, b, c){ 
                  dep1.grito(b);
                  dep2.haceOtraCosa();
              },
        ...
    };
    return service();
});

它有点不同,但它把它分解成一个 header 和一个原型函数列表,这是我喜欢的。