简单的问题是:我们需要在AngularJS工厂和服务中使用var self = this;
吗?在AngularJS Factory或Service中,我们是否需要设置一个“自我”或临时局部变量来记住“我自己”或“这个”?
我已经看到了工厂或服务,它使用一个var self = this;
记住本身(服务对象)AngularJS代码,然后的服务对象的内部的功能,使用self
指本身。 (有点像我们如何害怕我们会失去什么this
是,所以我们设置self = this
以后使用它,通过封闭的原则。
然而,我发现,我们可以放心地使用this
。为什么呢?因为我们找回单独服务对象,当我们调用myService.getNumber()
,该this
被绑定到服务对象myService
,所以它的工作,例如:
如果它是一个服务:
https://jsfiddle.net/yx2s3e72/
angular.module("myApp", [])
.service("myService", function() {
console.log("Entering factory");
this.s = "hello";
this.getLength = function() {
return this.s.length;
};
})
.controller("myController", function(myService) {
console.log("Entering controller");
var vm = this;
vm.s = myService.s;
vm.length = myService.getLength();
});
,或者如果它是一个工厂:
https://jsfiddle.net/935qmy44/
angular.module("myApp", [])
.factory("myService", function() {
console.log("Entering factory");
return {
s: "hello",
getLength: function() {
return this.s.length;
}
};
})
// controller code not repeated here...
它也能工作。那么是否真的不需要在自定义的AngularJS工厂或服务中设置var self = this;
?
在工厂返回对象,“这”是在对象的上下文。在服务单例中,“this”与您定义的函数绑定,非常类似于可以“新建”的任何其他函数“object” –
如果您使用其他回调,如'$ q'或'$ http'。没有任何其他嵌套函数作用域不同 – charlietfl