In AngularJS, is it more advisable to return a constructor
or an object
, of which we might then create new instances as needed?
As a pure JavaScript issue, this has been discussed here on SO. I want to understand this from a AngularJS best practices perspective, for two reasons:
- performance and memory are a big concern for my project;
- I am looking to upgrade to Angular 2, so I want to understand if my use of constructors will be problematic or against Angular2 best practices.
Currently I am doing this:
angular
.module('MyConstructorModule', [])
.service('MyConstructor', MyConstructor);
/* @ngInject */
function MyConstructor($http) {
var MyConstructor = function(url, getPar){
this.url = url;
this.getPar = getPar;
return this;
}
MyConstructor.prototype.getStuff = function() {
return $http({
method: 'GET',
url: this.url + this.getPar
});
}
return MyConstructor;
}
// Used in functions in which MyConstructor is Injected
new MyConstructor(myurl, myGetParams)
.getStuff()
.then(callback);
I find this very convenient, but my understanding is that it's not in line with AngularJS logic for services, which are singletons.
So, alternatively, I could do this:
angular
.module('MyConstructedObjectModule', [])
.factory('MyConstructedObject', MyConstructedObjectFactory);
/* @ngInject */
function MyConstructedObjectFactory($http) {
var constructedObject = {
init : init,
getStuff : getStuff,
vars : {}
}
function init(url, getPar) {
constructedObject.vars.url = url;
constructedObject.vars.getPar = getPar;
return constructedObject;
}
function getStuff() {
return $http({
method: 'GET',
url: constructedObject.vars.url + constructedObject.vars.getPar
});
}
}
// NOT TESTED
// Would be Used in functions in which MyConstructedObject is Injected
var newConstructedObject = _.cloneDeep(MyConstructedObject); // https://lodash.com/docs/4.15.0#cloneDeep
newConstructedObject
.init(myurl, myGetParams)
.getStuff()
.then(callback);
In this way I would be following AngularJS best practices. But then:
- would it be any easier to upgrade to Angular 2?
- would I have any gains or losses in terms of performance or memory usage?