我遵循了 http://www.tutorialspoint.com/angularjs/angularjs_services.htm 上的 AngularJS 教程
传递给 CalcService 服务的方法让我感到困惑。 Angular 是使用揭示原型(prototype)还是不同的原型(prototype)。我很困惑,因为在 this.square 中声明的内部函数应该是私有(private)的,并且在对象上下文之外不可见。 Angular 如何访问 square。
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
最佳答案
AngularJS 服务
是一个非常独特的东西。
初始化后,它会被new
ed。以此为例:
function CalcService() {
this.square = function() {
// square some stuff
};
}
// then in the controller, directive, or wherever,
// it gets initialized behind the scenes like this
new CalcService();
但是,它被初始化为单例,这意味着对该对象只有一个引用,即使您注册它的组件尝试重新初始化它(请参阅 my recent answer on singletons in AngularJS )。
不确定当你提到“揭示原型(prototype)模式”时你的意思,但是 this
在 AngularJS 服务的情况下,只是在新的常规方法上实现非原型(prototype)方法JavaScript 对象。
与上面的示例保持一致,在“正常”JavaScript 中,您可以调用 new CalcService().square()
。 JavaScript 没有任何私有(private)方法的 native 概念(尽管有一些方法可以实现看似私有(private)的“类”方法。)
var service = new CalcService();
service.square();
该方法没有什么“私有(private)”的,就像附加到 AngularJS 服务对象的方法没有什么“私有(private)”的一样......它唯一远程“私有(private)”的事情是它恰好只属于 凭借 this
关键字到达该特定对象。
关于Angular 中使用的 JavaScript 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31759120/