在AngularJS中,建议您返回constructor
或object
,我们可能会根据需要创建新实例吗?
作为纯JavaScript问题,我们已经讨论过here on SO。我想从AngularJS最佳实践的角度来理解这一点,原因有两个:
目前我这样做:
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);
我觉得这很方便,但我的理解是它与服务的AngularJS逻辑不一致,singletons。
所以,或者,我可以这样做:
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);
通过这种方式,我将遵循AngularJS的最佳实践。但那时: