I read some tutorials for AngularJS and noticed, that everyone is using a slightly different approach how to define a service. I'm wondering whats the best method, or what drawbacks could arise when using a specific approach.
The first difference I noticed, is in using an anonymous function OR a named function:
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
angular.module('myApp').service('myService', function() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
- Is there any difference in this two methods?
- Does angular provide the
myService
named function? And how?
The second difference is in defining the "public methods", e.g. what is visible to the outside:
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
var public_methods = {
doSomething: function() {
return "bar";
},
var1: _var1
};
return public_methods;
});
angular.module('myApp').service('myService', function myService() {
var _var1 = "foo";
this.doSomething = function() {
return "bar";
};
this.var1 = _var1
});
The first one returns an object, which acts like an interface and defines what is visible to the public. The second one, defines its methods and properties with this
.
- Are there any drawbacks?
- Why would I prefer one method over the other?
The third difference is on defining services like this:
var Session = function() {};
Session.prototype.doSomething = function() {
return "bar";
};
Session.prototype.var1 = "foo";
angular.module('myApp').service('myService', Session);
Here, I only see one drawback, that privat variables cannot be shared with other functions. But does this method has any big advantages? I could imagine that for factories (not services) the performance would be better, because the prototype functions only has to be defined once, and not everytime a new object is created (because a service is a singleton, a factory not).
Defining and using factories: I'm also unsure, if the following method is best practise when using factories:
angular.module('myApp').factory('User', function() {
var User = function(data) {
angular.extend(this, {
id: null,
email: null,
name: null
}, data);
};
return User;
});
And when using the factory, I'm writing new User(data)
. data
gets merged with some default variables etc. What do you think about this method? Is there a big drawback? Or am I using factories in a wrong way?