为什么词法 this 运行 作为我的 lambda 函数中的另一个上下文?
Why is lexical this run as another context in my lambda function?
我已经创建了使用 Google API 来获取数据的服务页面,现在我想要 运行 来自打开服务页面的页面的回调函数,尽管我遇到了问题优雅地处理上下文。
我第一页的精简版如下所示:
import {Page, NavController} from 'ionic-angular';
import {BarPage} from '../barPage/barPage';
@Page({
templateUrl: 'build/pages/foo/foo.html'
})
export class FooPage {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
this.nav = nav;
}
//...skipping code
processData(data) {
// do something
}
openFindPlacePage(event) {
let self = this;
this.nav.push(BarPage,
{
onSelect: (data) => {
//this.processData(data); Runs with the wrong context
self.processData(data);
}
});
}
}
我的助手class是这样的:
import {Page, NavController, NavParams} from 'ionic-angular';
@Page({
templateUrl: 'build/pages/barPage/barPage.html'
})
export class BarPage {
static get parameters() {
return [[NavController], [NavParams]];
}
constructor(nav, navParams) {
this.nav = nav;
if (navParams.data.onSelect)
this.onSelect = navParams.data.onSelect;
}
//...skipping code
placeSelected() {
// this.autocomplete was defined elsewhere
let placeInfo = this.autocomplete.getPlace();
if (this.onSelect)
this.onSelect(placeInfo);
this.nav.pop();
}
}
这个解决方案对我有用,因为我很困惑为什么我必须使用 self = this 来调用 processData 而不是 this 正如我希望能够在 lambda 函数中那样。
尽管在源映射中查看时 Chrome 的开发工具仍然在我的 lambda 函数中显示 this 的不正确上下文,重新启动后代码能够正确执行。
这对我来说似乎很奇怪,但我不知道它需要回答,因为代码现在正在按预期执行。
我已经创建了使用 Google API 来获取数据的服务页面,现在我想要 运行 来自打开服务页面的页面的回调函数,尽管我遇到了问题优雅地处理上下文。
我第一页的精简版如下所示:
import {Page, NavController} from 'ionic-angular';
import {BarPage} from '../barPage/barPage';
@Page({
templateUrl: 'build/pages/foo/foo.html'
})
export class FooPage {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
this.nav = nav;
}
//...skipping code
processData(data) {
// do something
}
openFindPlacePage(event) {
let self = this;
this.nav.push(BarPage,
{
onSelect: (data) => {
//this.processData(data); Runs with the wrong context
self.processData(data);
}
});
}
}
我的助手class是这样的:
import {Page, NavController, NavParams} from 'ionic-angular';
@Page({
templateUrl: 'build/pages/barPage/barPage.html'
})
export class BarPage {
static get parameters() {
return [[NavController], [NavParams]];
}
constructor(nav, navParams) {
this.nav = nav;
if (navParams.data.onSelect)
this.onSelect = navParams.data.onSelect;
}
//...skipping code
placeSelected() {
// this.autocomplete was defined elsewhere
let placeInfo = this.autocomplete.getPlace();
if (this.onSelect)
this.onSelect(placeInfo);
this.nav.pop();
}
}
这个解决方案对我有用,因为我很困惑为什么我必须使用 self = this 来调用 processData 而不是 this 正如我希望能够在 lambda 函数中那样。
尽管在源映射中查看时 Chrome 的开发工具仍然在我的 lambda 函数中显示 this 的不正确上下文,重新启动后代码能够正确执行。
这对我来说似乎很奇怪,但我不知道它需要回答,因为代码现在正在按预期执行。