为什么要在lambda函数中作为另一个上下文运行?
我已经创建了一个服务页面,它可以与GoogleAPI一起获取数据,现在我想从打开服务页面的页面运行一个回调函数,尽管我在优雅地处理上下文方面遇到了困难 我的第一页的精简版本如下所示:为什么要在lambda函数中作为另一个上下文运行?,lambda,ecmascript-6,ionic2,Lambda,Ecmascript 6,Ionic2,我已经创建了一个服务页面,它可以与GoogleAPI一起获取数据,现在我想从打开服务页面的页面运行一个回调函数,尽管我在优雅地处理上下文方面遇到了困难 我的第一页的精简版本如下所示: import {Page, NavController} from 'ionic-angular'; import {BarPage} from '../barPage/barPage'; @Page({ templateUrl: 'build/pages/foo/foo.html' }) export
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);
}
});
}
}
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();
}
}
我的助手类是这样的:
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);
}
});
}
}
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,而不是我希望在lambda函数中使用的This。尽管Chrome的开发工具在源代码映射中查看时仍然在我的lambda函数中显示不正确的上下文,重新启动后,代码能够正确执行
这对我来说似乎很奇怪,但我不知道它是否需要回答,因为代码正在按预期执行。此代码是在哪个环境中执行的?听起来像是引擎中的一个bug,缺少ES6支持。@FelixKling我正在Chrome浏览器中执行linux上运行TypeScript的项目。@Bergi,但在类似这样的地方使用时,我能够获得正确的上下文。storage.get('baz')。然后((数据)=>{//do something})@菲尔德。编译为ES6或ES5的类型脚本?发丝结果正确吗?您是否安装了最新版本的TS和Chrome?