2017-06-01 69 views
2

嘿,有人能告訴我如何在foreach循環中訪問組件變量? 這裏我 PlunkerTypescript如何訪問foreach循環中的組件變量?

public testVariable:number; 

    test(){ 
    console.log('fired'); 
    var x =[1,2,3,4]; 

    x.forEach(function (e){ 
     this.testVariable = e; 
    }) 

    console.log(this.testVariable); 
    } 
+1

[如何在回調中訪問正確的\'this \'上下文?](https://stackoverflow.com/questions/20279484 /如何訪問這個正確的回調這個上下文) – echonax

回答

11

如果使用function (e)this裏面將參考函數的作用域而不是類。

使用Arrow Function(或Fat Arrow)代替:

x.forEach((e) => { 
    this.testVariable = e; 
}) 

只有1個參數時,您也可以忽略周圍的括號:

x.forEach(e => { 
    this.testVariable = e; 
}) 

這裏有一個很好的文章,解釋它的行爲: https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

+1

這樣的結果總是不會'4'?另外,並不是所有的匿名函數「lambda」? – evolutionxbox

+1

@evolutionxbox你是正確的,lambda是匿名函數的同義詞,我糾正了答案。感謝您的高舉 – borislemke

4

this值取決於你所在的範圍內考慮做這樣的:

public testVariable:number; 

test(){ 
    console.log('fired'); 
    var x =[1,2,3,4]; 

    var self = this; 
    x.forEach(function (e){ 
     self.testVariable = e; 
    }) 

    console.log(this.testVariable); 
} 
+0

你的實現對es5是必需的,但在typescript等中是過時的 – Jacques