TS TypeScript SetInterval - 无法从定时器目标函数内部访问函数

时间:2017-04-13 07:14:49

标签: javascript typescript setinterval

我试图从setInterval()调用的定时函数内部调用一个函数。

这是我的代码:

export class SmileyDirective
{

FillGraphValues()    
{
    console.log("FillGraphValues works");      // this works
}

MyTimer()
{
    console.log("timer works");      // this works
    this.FillGraphValues();          // this does not work
    FillGraphValues();               // this does not work
}

draw()
{
    this.FillGraphValues();    // this works

    setInterval(this.MyTimer, 1000);
}
} 

应用程序崩溃:

"this.FillGraphValues is not a function"

Cannot find name 'FillGraphValues'. Did you mean the instance member 'this.FillGraphValues'?

我甚至尝试过:

setInterval(function(){MyTimer()}, 1000);

setInterval(function(){this.MyTimer()}, 1000);

但他们没有用。

非常感谢:)

1 个答案:

答案 0 :(得分:0)

也许这会奏效:     setInterval(()=> {this.MyTimer()},1000);

因此代码如下所示:

export class SmileyDirective {

    FillGraphValues() {
        console.log("FillGraphValues works");      // this works
    }

    MyTimer() {
        console.log("timer works");      // this works
        this.FillGraphValues();          // this DOES work
    }

    draw() {
        this.FillGraphValues();    // this works

        setInterval(() => { this.MyTimer() }, 1000);
    }
}

var obj = new SmileyDirective();
obj.draw(); 

这完全转变为:

define(["require", "exports"], function (require, exports) {
    "use strict";
    var SmileyDirective = (function () {
        function SmileyDirective() {
        }
        SmileyDirective.prototype.FillGraphValues = function () {
            console.log("FillGraphValues works"); // this works
        };
        SmileyDirective.prototype.MyTimer = function () {
            console.log("timer works"); // this works
            this.FillGraphValues(); // this does not work
        };
        SmileyDirective.prototype.draw = function () {
            var _this = this;
            this.FillGraphValues(); // this works
            setInterval(function () { _this.MyTimer(); }, 1000);
        };
        return SmileyDirective;
    }());
    exports.SmileyDirective = SmileyDirective;
    var obj = new SmileyDirective();
    obj.draw();
});

要注意的部分是

 var _this = this;
            this.FillGraphValues(); // this works
            setInterval(function () { _this.MyTimer(); }, 1000);

通过在闭包中保存 this 变量并在setInterval调用函数时使用它来实质上保留上下文。