简体   繁体   中英

Why are Angular.js Services created with 'new'?

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 =\\

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.

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