1

As per the angular js docs

service(name, constructor); name : name constructor : An injectable class (constructor function) that will be instantiated.

Internally :
{
  $get: function() {
    return $injector.instantiate(constructor);
  }
}

It could be concluded from the angular docs that service treats the 2nd argument passed as a constructor and provider creates an instance through $injector and returns through $get. So whenever we will inject the service in any of our module functions(controllers , directives etc) it should return the newly created object which is Singleton offcourse.

Now the problem comes here if I define my service like these ways.

1. _app_user_content.service("MyService" , function(){
        this.Message = "Greetings!";
    });  //returns object when injected.
2. _app_user_content.service("MyService" , function(){
        this.Message = "Greetings!";
        return "123"
    }); // returns object  when injected.
3. _app_user_content.service("MyService" , function(){
        this.Message = "Greetings!";
        return function(){}
    }); //returns function(){}  when injected. Doesnot return object

Why does the third case return a function?

Alex Logan
  • 1,221
  • 3
  • 18
  • 27
ajaykumar
  • 646
  • 7
  • 17

1 Answers1

3

This is a JavaScript thing, more than an angular thing.

What an angular service does is basically use your function as a constructor by doing new SomeObject(), SomeObject being the function you defined in the second argument (important to note that in JavaScript functions are objects).

If your function returns nothing or a primitive value, the constructor will ignore your return value and instead return whatever you've set on the scope (this) of that function. If, however, you return an object, it seems the constructor will return that object instead. (Thanks @ajaykumar)

Try this in browser console...

function potato() {this.yummy = true; return function() {};} 
function tomato() {this.yummy = true;}
console.log(new potato());
console.log(new tomato());

You should see potato return function () {}.

You should see tomato return {yummy: true}.

For constructor functions such as this, I would recommend returning nothing.

If however you were to use angular's factory method, you will find that instead of doing new SomeObject() angular will do return SomeObject(), in which case you want to return an object with any functions / parameters you want to expose in your service.

More info on the JavaScript new keyword, prototypes and constructor functions here.

ed'
  • 1,815
  • 16
  • 30
  • 1
    Your answer is pointing correctly to javascript syntactical fundamentals. Further investigating, I could conclude that if the function returns javascript primitives it returns the newly created object. However if the return statement includes other than primitive types it simply assigns the return statement and does not create an object. – ajaykumar May 31 '16 at 10:51