【问题标题】:Typescript Nested This Not Calling Defined Function打字稿嵌套了这个不调用定义的函数
【发布时间】:2016-09-06 05:41:43
【问题描述】:

我正在开发一个使用 Ionic 2 Beta 和 Typescript 的应用程序。当this 嵌套在 Typescript 中时,我遇到了某种错误,但我无法完全理解它。这是我的代码:

constructor(public navCtrl: NavController, params: NavParams, platform: Platform) {
    platform.ready().then((readySource) => {
        try {
            this.num = params.get("num");
            this.unprocData = params.get("data");
            var image = <HTMLImageElement>document.getElementById('unprocImg');
            image.src = this.unprocData;
            image.onload = function() { console.log("images loaded"); this.proc(this.num); }
            //some stuff
        } catch (err) {
            console.log("Problem Starting Render // " + err);
            this.navCtrl.push(IndexPage);
        }
    });
}

proc(num) {
    try {
        console.log("starting render...");
        switch(num) {
            case 0:
                this.procImg1(function() { //process the image for default vintage greyscale
                    this.load(this.procData, this.descriptionPoster1, "assets/img/Poster1.png", 250, 310, .6, .6);
                }); break;
            ..
        }
    } catch (err) {
        console.log("Problem Starting Render // " + err);
        this.navCtrl.push(IndexPage);
    }
}

test() {
    this.proc(0);
}

有趣的是,函数 test() 按预期工作,但是当从 image.onload(..) 内部调用 this.proc(..) 时,我收到错误 this.proc is not a function。我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: javascript typescript ionic-framework nested this


    【解决方案1】:

    问题在于this 在以下情况下有所不同:

    image.onload = function() { console.log("images loaded"); this.proc(this.num); }
    

    已执行,这是因为您使用的常规函数​​在执行时不会保存 this 的上下文(它是异步的)。

    你可以这样做:

    (1) 使用上面的箭头函数:

    image.onload = () => { console.log("images loaded"); this.proc(this.num); }
    

    (2) 使用bind:

    image.onload = function() { console.log("images loaded"); this.proc(this.num); }.bind(this)
    

    【讨论】:

      猜你喜欢
      • 2019-08-03
      • 2019-07-30
      • 2015-08-21
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 2020-05-02
      • 2019-07-30
      • 1970-01-01
      相关资源
      最近更新 更多