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.

链接地址: http://www.djcxy.com/p/77996.html

上一篇: 解析一个函数并使用其副作用来记录服务中的数据

下一篇: 为什么用'新'创建Angular.js服务?