简体   繁体   中英

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. 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?

[ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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