setInterval behaviour in TypeScript

后端 未结 1 1784
暖寄归人
暖寄归人 2021-02-18 17:48

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 th

1条回答
  •  既然无缘
    2021-02-18 18:42

    I am assuming that span is a property in the same class as the start method... Correct me if I am wrong on this.

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

    When you use () => TypeScript preserves the lexical scope... which just means this means 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 _this to do that.

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

    You can use this basic test to see the difference by calling withFatArrow or withoutFatArrow and you'll see what happens.

    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();
    

    0 讨论(0)
提交回复
热议问题