简体   繁体   English

Angular JS工厂如何工作?

[英]How does Angular JS factory work?

Is there any difference between this two factories? 这两家工厂有什么区别吗?

.factory("f1", function(){
  var F1 = function() { ... }
  ...

  return F1;
})

and

.factory("f2", function(){
  var F2 = function() { ... }
  ...

  return new F2();
})

I know f1 returns a constructor and f2 returns an instance of object but idea of a factory is returning instances of an object. 我知道f1返回构造函数, f2返回对象的实例,但是工厂的想法是返回对象的实例。 In many tutorials about angular I've seen construction like f1 and I start to thing about how this factory works, maybe they create an instance of an object automatically and the new operator is useless? 在许多有关角度的教程中,我已经看到过像f1这样的构造,并且我开始研究该工厂的工作方式,也许它们会自动创建对象的实例,而new运算符是没有用的?

[ EDIT ] [ 编辑 ]

What you thing about this solution 您对这个解决方案有何看法

.factory("f3", function(options){
  var F3 = function() { ... }
  ...

  var init = function (options){
    return new F3(options);
  }

  return {createInstance: init);
})

yes. 是。 first returns class definition and second returns instance of class definition. 第一个返回类定义,第二个返回类定义实例。

If you need to create instance of an object multiple time, then you can return prototype from factory. 如果需要多次创建对象的实例,则可以从工厂返回原型。 If you want to initialize it once then return new from factory. 如果要初始化一次,请从工厂返回新值。

Factory and service are singleton. 工厂和服务都是单例。 So if you want to use object multiple times then return class definition. 因此,如果您想多次使用对象,则返回类定义。 So you can do multiple times new in your controllers. 因此,您可以在控制器中多次执行新的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM