Bind "this" to TypeScript Lambda

5.3k Views Asked by At

Say I have a lambda in TypeScript:

 myArray.forEach(o => o.x = this.x);

The value of this becomes window instead of the calling object. What I'd really like to do is:

 myArray.forEach(o => { o.x = this.x; }.bind(this));

But I don't see that as an option in TypeScript. How can I override this in a TypeScript lambda body?

1

There are 1 best solutions below

3
On

Just FYI even without a lambda the default this in a for each is window e.g. :

[1].forEach( function ( o ) { console.log( this ) }); // window

To fix the this with bind you need to use a function and not a lambda (which lexically scopes the meaning of this).

var foo = {};
[1].forEach( function ( o ) { console.log( this ) }.bind( foo ) ); // object `foo`

Alternatively you can use the second argument for forEach as mentioned by Bergi.