【问题标题】:Can't access local property from within Callback in Ionic2无法从 Ionic2 的回调中访问本地属性
【发布时间】:2016-10-16 18:09:45
【问题描述】:

我有一个基本的 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 范围。

我必须在这里做一些简单的事情,但我不正确理解新的范围。

【问题讨论】:

    标签: javascript angular ecmascript-6 ionic2


    【解决方案1】:

    你应该有一个箭头函数才能使用词法 this:

    asyncMethodWithCallBack((result) => 
       {
           this.id = result; //Cannot find this.id
       });
    

    从 MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) 中提取:

    直到箭头函数,每个新函数都定义了自己的 this 值(在构造函数的情况下是一个新对象,在严格模式函数调用中未定义,如果函数被称为“对象方法”,则为上下文对象等) .事实证明,这对于面向对象的编程风格来说很烦人。

    箭头函数捕获封闭上下文的 this 值。

    【讨论】:

    • 看准了!谢谢 :) 在我的情况下 delegate.method = (args) => { return something; }
    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多