问题描述:

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.

相关阅读:
Top