gpt4 book ai didi

javascript - 无法从 Ionic2 的回调中访问本地属性

转载 作者:行者123 更新时间:2023-11-28 15:08:26 25 4
gpt4 key购买 nike

我有一个基本的 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.

关于javascript - 无法从 Ionic2 的回调中访问本地属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37838623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com