无法从 Ionic2 的回调中访问本地 属性
Can't access local property from within Callback in Ionic2
我有一个基本的 Ionic 2 应用程序,它使用 Angular2。我有一个相当基本但令人沮丧的问题。这是我的组件...
import {Component} from "@angular/core";
@Component({
'<ion-content>{{id}}</ion-content>
});
export class ListPage {
constructor(nav, navParams) {
this.id = "123";
//This could be any method (ajax call or just an event emitter)
asyncMethodWithCallBack(function(result)
{
this.id = result; //Cannot find this.id
}
}
}
问题是当我的应用程序尝试将自己附加到一个接受回调的方法时,当回调触发时,它不再能够找到 this.id 范围。
我一定是在这里做了一些简单的事情,但我没有正确理解新的范围。
你应该有一个箭头函数才能使用词法 this:
asyncMethodWithCallBack((result) =>
{
this.id = result; //Cannot find this.id
});
摘自 MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions):
Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.
Arrow functions capture the this value of the enclosing context.
我有一个基本的 Ionic 2 应用程序,它使用 Angular2。我有一个相当基本但令人沮丧的问题。这是我的组件...
import {Component} from "@angular/core";
@Component({
'<ion-content>{{id}}</ion-content>
});
export class ListPage {
constructor(nav, navParams) {
this.id = "123";
//This could be any method (ajax call or just an event emitter)
asyncMethodWithCallBack(function(result)
{
this.id = result; //Cannot find this.id
}
}
}
问题是当我的应用程序尝试将自己附加到一个接受回调的方法时,当回调触发时,它不再能够找到 this.id 范围。
我一定是在这里做了一些简单的事情,但我没有正确理解新的范围。
你应该有一个箭头函数才能使用词法 this:
asyncMethodWithCallBack((result) =>
{
this.id = result; //Cannot find this.id
});
摘自 MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions):
Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.
Arrow functions capture the this value of the enclosing context.