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?
Just FYI even without a lambda the default
this
in a for each iswindow
e.g. :To fix the this with
bind
you need to use afunction
and not a lambda (which lexically scopes the meaning ofthis
).Alternatively you can use the second argument for
forEach
as mentioned by Bergi.