Simon Staton
Simon Staton

Reputation: 4505

AngularJS : some help understanding service/factory

I have spent hours reading about the differences between a service and factory both on here, on the angular docs and in other places however I still don't really understand it.

I know there are already countless posts on here relating to this subject however I just want to make sure I am understanding correctly as I'm either missing something or there is no reason for the differentiation... From what I understand a service and a factory do the exact same thing, they are identical in functionality and the only difference is in the architecture.

If we were to ignore angular for a moment and recreate this in vanilla JS am I correct in thinking this is how each work:

//factory design
var factoryDesign = function(){

    var privateFoobar = 'foobar',
        reverse = function(){ 
            return privateFoobar
                .split('')
                .reverse()
                .join('');
        }

    return {
        foobar: privateFoobar,
        raboof: reverse()
    }

};

//Service design
var serviceDesign = function(){
    this.foobar = 'foobar';
    this.raboof = this.foobar    
        .split('')
        .reverse()
        .join('');
}

var myGlobalServiceInstance = new serviceDesign(),
    myGlobalFactoryInstance = new factoryDesign();

console.log('service', myGlobalServiceInstance.foobar, myGlobalServiceInstance.raboof);

console.log('factory',myGlobalFactoryInstance.foobar,myGlobalFactoryInstance.raboof);

JSFIDDLE

Both of these instances will return the same thing however the factory relies mainly on private objects which are simply returned and the service scopes methods and objects to the instance.

If this is the case.... what exactly is the point of this? Is there any reason for differentiating a factory... I understand with the service it will allow you to change values such as:

myGlobalServiceInstance.foobar = 'newFoobar';

But what are the benefits of using a factory? If possible please provide any examples in vanilla JS

Upvotes: 2

Views: 231

Answers (1)

David Losert
David Losert

Reputation: 4802

To be short: With a service, angular delivers you the instantiation of the function you pass in. So: service('myService', function myService(){}); is the same as new myService();,

while with a factory, angular delivers what is returned by the function you pass in: factory('myFactory', function myFactory(){}); is the same as myFactory();

So with a factory, you can for example pass your own class / constructor-functio ndefinition and instantiate it elsewhere in your Code, something like:

factory('myFactory', function(){
    var MyClass = function(){};

    return MyClass ;
});

Upvotes: 1

Related Questions