TypeScript: Lambdas and using 'this'

5k views Asked by At

JavaScript frameworks often call callbacks using apply().

TypeScript's arrow notation, however, doesn't seem to allow me to access the 'this' pointer.

How's it done?

If it isn't, is there a place to down-vote the current 'this' handling on Lambdas?

2

There are 2 answers

2
David Sherret On BEST ANSWER

TypeScript's handling of this in arrow functions is in line with ES6 (Read: Arrow Functions). Due to that specification, it would be inconsistent for it to act any other way.

If you want to access this of the current function, then you can use a regular function.

For example, change:

function myScope() {
    var f = () => console.log(this); // |this| is the instance of myScope
    f.call({});
}

new myScope();

To:

function myScope() {
    var f = function() { console.log(this); } // |this| is {}
    f.call({});
}

new myScope();
0
Konkret On

One way to have the Lambda function working with the keyword this, is to have it inside a class.

In the following example, the function employee2 will not compile:

// Using a method defined as a lambda function
class Company{
    private id : number
    private name : string;

    public employee = (id : number, name : string) => {
        this.id = id;
        this.name = name;
    }
}

// Using a function declaration
function employee1(id : number, name : string){
    this.id = id;
    this.name = name;
}

// Using a lambda function
const employee2 = (id : number, name : string) => {
    this.id = id;
    this.name = name;
}

// Using a function expression
const employee3 = function(id : number, name : string){
    this.id = id;
    this.name = name;
}