我正在将控制器调整为"controller as"语法。但是在转换代码时,我注意到我不能在函数外访问"scope"变量。如果我理解这个概念,那么它确实访问了它所使用的对象。例如,此代码:
this.scopeVariable = undefined;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
this.scopeVariable = result.foo;
});
};
所以,当我试图用这个设置scopeVariable时,我实际上试图从fooFunction访问一个对象,对吧?如果是这种情况,如何在函数内获取函数外的对象?
谢谢你的回答!
您会遇到这个问题,因为this
关键字在不同的作用域中会更改定义。这意味着,如果你有一个简单的对象,例如
var a = {
b: function() {
console.log(this); // => will log the value of "a"
setTimeout(function() {
console.log('just some rubbish');
console.log(this); // => will log inner function scope instead of "a"
}, 200)
}
}
a.b(); // to see the results
为了防止此问题发生,您可以将this
重新分配给一个变量,该变量将在更深的范围内保持不变,如
this.scopeVariable = undefined;
var self = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
// using self. instead of this. makes the difference here
self.scopeVariable = result.foo;
});
};
捕获作为变量中作用域的this
:var that = this
:
var that = this;
this.fooFunction = function () {
resource.get()
.$promise.then(function (result) {
that.scopeVariable = result.foo;
});
};