4

According to this question:

angular.service vs angular.factory

Services are created by angular with the new keyword, meaning a new instance of the returned object.

For example:

app.service('helloWorldService', function() {
    this.hello = function() {
        return "Hello World"; };
    }
);

However, with factories, they are not.

Meaning a developer can, if they choose, to create new instances (by using the keyword new) - hence, why its called a factory I assume.

My question is:

Why is angular creating a new instance of a service to begin with?

I agree that services should singletons, which they are, but whats the point of creating a new instance of the returned function? Wouldn't it be better, for services, if Angular just returned the declared function - just as they do with factories.

Doesn't that make more sense for services?

The reason I am asking is because I am, on an abstraction layer, creating services, but I am unsure if I should really use the services API over the factories API, just because creating a new instance of the declared function seems a bit pointless and overkill =\

SoEzPz
  • 14,958
  • 8
  • 61
  • 64
corgrath
  • 11,673
  • 15
  • 68
  • 99
  • I want to preface this by saying I am new to angular and development in general. It seems that the only way the service would make sense is to instantiate them in a different way, but they are not set up to easily have parameters passed in since you pass in dependencies into the anonymous function. I've read all the related answers on SO as well, and I too am wondering what purpose the "new" serves. In practice, I am satisfied in using factories to either return new {} to have one shared object, or return a class(){} and new it myself to create instances. – 1mike12 Feb 16 '15 at 18:54

1 Answers1

0

If you research this very informative link

Informative Link on SO

And yet another link on SO

Just in case the first two SO links were missed, here is yet another

you will find that the only difference between a factory, service, and provider is Anguljarjs overhead code that runs to support the feature.

In the case of service or factory as you mentioned, the service will utilize this.property, and perhaps include its own prototypal chain of function additions, and normal JS constructor actions.

You could do all of this inside of a factory wrapper as well, but you would not instantiate the factory in your controller/directives using the 'new' operator.

Community
  • 1
  • 1
SoEzPz
  • 14,958
  • 8
  • 61
  • 64