5
私はいくつかのタイスクリプトコードを書いていて、配列を反復しています。ループ内で、私はいくつかの処理を行うには「この」オブジェクトにアクセスしようとしています:foreachループ内で 'this'は未定義です
console.log('before iterate, this = ' +this);
myarray.days.forEach(function(obj, index) {
console.log('before transform, this : ' + this);
this.datePipe.transform...
});
をしかしそれは、これは '[対象オブジェクトとして 「この」オブジェクトが正しく印刷定義されていないと文句を言い、これは失敗しました]ループの前/外側にありますが、ループの内部では未定義です。何故ですか?そしてそのための修正は何ですか?
myarray.days.forEach((obj, index) => {
console.log('before transform, this : ' + this);
this.datePipe.transform...
});
またはbind methodを使用します:
myarray.days.forEach(function(obj, index) {
console.log('before transform, this : ' + this);
this.datePipe.transform...
}.bind(this));
理由は、それがthis
呼び出されたときに、コールバックとして通常の関数を渡すときにということであるあなたがarrow functionを使用するか必要