假设我在TypeScript中有一个lambda:
myArray.forEach(o => o.x = this.x);
this
的值变为window
而不是调用对象。我真正想做的是: myArray.forEach(o => { o.x = this.x; }.bind(this));
但是我不认为这是TypeScript中的选项。如何在TypeScript Lambda主体中覆盖
this
? 最佳答案
即使没有lambda,也只是仅供引用,每个中的默认this
是window
例如。 :
[1].forEach( function ( o ) { console.log( this ) }); // window
要使用
bind
修复此问题,您需要使用function
而不是lambda(这在词法上限制了this
的含义)。var foo = {};
[1].forEach( function ( o ) { console.log( this ) }.bind( foo ) ); // object `foo`
或者,您可以使用Bergi提到的
forEach
的第二个参数。