setInterval behaviour in TypeScript

javascript, typescript

Solution

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

Problem

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. 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. In JavaScript that would be equivalent to this: ``` 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. So easy question ... why?

Original source