After reading multiple tutorials on AngularJS, it became evident that there are various approaches to defining a service. I am now curious about the best practices and potential drawbacks associated with each method.
The initial difference I observed relates to using an anonymous function versus 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 distinction between these two methods?
- Does angular support the
myService
named function? If so, how?
A secondary disparity emerges in defining the "public methods," specifically regarding what is visible externally:
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
});
In the first scenario, an object is returned to act as an interface, outlining what is publicly accessible. The second approach defines methods and properties using this
.
- Are there any disadvantages?
- What factors would lead me to prefer one methodology over the other?
The third variation involves defining services like this:
var Session = function() {};
Session.prototype.doSomething = function() {
return "bar";
};
Session.prototype.var1 = "foo";
angular.module('myApp').service('myService', Session);
In this case, the only drawback seems to be the inability to share private variables across functions. Are there significant advantages to this approach? It's conceivable that for factories (as opposed to services), performance may improve since prototype functions need not be redefined every time a new object is created (given that a service is a singleton while a factory is not).
Defining and utilizing factories: I question whether the following method represents the best practice when employing factories:
angular.module('myApp').factory('User', function() {
var User = function(data) {
angular.extend(this, {
id: null,
email: null,
name: null
}, data);
};
return User;
});
When utilizing the factory, I instantiate new User(data)
, where data
merges with default variables. What are your thoughts on this technique? Are there significant drawbacks or am I potentially misusing factories?