When using "function.call()" syntax, "=>" style functions should not retain "this".

Topics: General, Language Specification
Jan 21, 2013 at 5:18 AM

A simple example:

 

    var t = function (cb, ct) {
        cb.call(ct);
    }

    t(function () {
        console.log(this);
    }, {});

    t( () => {
        console.log(this);
    }, {});

This is a common Javascript syntax for specifying what context a function should run in.  When using regular function syntax, it works as expected.  When using "=>" style syntax, the compiler creates an "_this" variable and uses it inside of the "cb" function.  

I'm guessing that is a specific choice when using the "=>" syntax, however, I feel like in the specific situation where "cb" is run via "cb.call()" and not just "cb()" that "this" should NOT be changed as it specifically goes against what the code is trying to accomplish.

Jan 21, 2013 at 4:41 PM

The arrow functions this is constrained to the context, which they were created.  This is part of the EMCAScript 6 specification, that TypeScript is trying to match as closely as possible.