Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Lambdas and using 'this'

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?

like image 337
AxD Avatar asked Mar 01 '26 13:03

AxD


1 Answers

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();
like image 61
David Sherret Avatar answered Mar 04 '26 11:03

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!