TypeScript 中的 setInterval 行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16077565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:03:37  来源:igfitidea点击:

setInterval behaviour in TypeScript

javascripttypescript

提问by seveves

I just started to play around with TypeScript. I′ve created a sample project with Visual Studio 2012 Express for Web and this sample has a line of code which has a behaviour that I cannot explain myself.

我刚开始玩 TypeScript。我已经使用 Visual Studio 2012 Express for Web 创建了一个示例项目,这个示例有一行代码,我无法解释自己的行为。

First the TypeScript code:

首先是打字稿代码:

start() {
    this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
}

So this line sets the value of timerToken every 500ms and updates a HTML element with the current Date/Time.

因此,此行每 500 毫秒设置一次 timerToken 的值,并使用当前日期/时间更新 HTML 元素。

In JavaScript that would be equivalent to this:

在 JavaScript 中,这相当于:

Greeter.prototype.start = function () {
        this.timerToken = setInterval(this.span.innerHTML = new Date().toUTCString(), 500);
    };

So I wondered about the lambda expression in the TypeScript code line and removed it but then the Date/Time string won't be updated anymore.

所以我想知道 TypeScript 代码行中的 lambda 表达式并将其删除,但随后日期/时间字符串将不再更新。

So easy question ... why?

这么简单的问题……为什么?

回答by Fenton

I am assuming that spanis a property in the same class as the startmethod... Correct me if I am wrong on this.

我假设这span是与start方法在同一类中的属性...如果我错了,请纠正我。

So the fat-arrow syntax has special meaning in TypeScript.

所以胖箭头语法在 TypeScript 中有着特殊的意义。

When you use () =>TypeScript preserves the lexical scope... which just means thismeans the same inside the expression as it does outside of the expression. You can see in the compiled JavaScript that it creates a variable named _thisto do that.

当您使用() =>TypeScript 时会保留词法作用域……这只是意味着this在表达式内部与在表达式外部的含义相同。您可以在编译后的 JavaScript 中看到它创建了一个名为的变量_this来执行此操作。

So with the fat-arrow syntax, this.spanis the property named span on your class. Without the fat-arrow syntax, this.spanis undefined.

因此,使用fat-arrow 语法,this.span您的类中的属性名为span。如果没有粗箭头语法,this.span则未定义。

You can use this basic test to see the difference by calling withFatArrowor withoutFatArrowand you'll see what happens.

您可以使用此基本测试通过调用withFatArrow或来查看差异withoutFatArrow,您将看到会发生什么。

class Test {
    public example = 'Test';
    private timer;

    withFatArrow() {
        this.timer = setTimeout(() => alert(this.example), 500);
    }

    withoutFatArrow() {
        this.timer = setTimeout(function() { alert(this.example) }, 500);
    }
}

var test = new Test();
//test.withFatArrow();
test.withoutFatArrow();