2017-07-18 53 views
1

我喜歡Node.js和JavaScript。我有例子類:如何在內部調用例如forEach在類中?

class Student { 
    constructor(name, age) { 
     this.name = name; 
     this.age = age; 
    } 
    getStudentName() { 
     return this.name; 
    } 
    getStudentAge() { 
     return this.age; 
    } 
    exampleFunction() { 
     let array = ['aaa', 'bbb', 'ccc', 'ddd']; 
     array.forEach(function(i, val) { 
      console.log(i, val); 
      console.log(this.getStudentName()); // ERROR! 
     }) 
    } 
} 

var student = new Student("Joe", 20, 1); 
console.log(student.getStudentName()); 
student.exampleFunction(); 

如何從這個類中的forEach函數中引用一個方法?

我有類型錯誤:

TypeError: Cannot read property 'getStudentName' of undefined

+0

胖箭頭功能FTW! 'array.forEach((i,val)=> {' – epascarello

回答

0

'this'在for循環內部發生變化。你必須強制它的定義。有幾種方法可以做到這一點。這裏是一個

class Student { 
    constructor(name, age) { 
     this.name = name; 
     this.age = age; 

    } 
    getStudentName() { 
     return this.name; 
    } 
    getStudentAge() { 
     return this.age; 
    } 
    exampleFunction() { 
     let array = ['aaa', 'bbb', 'ccc', 'ddd']; 
     array.forEach(function(i, val) { 
      console.log(i, val); 
      console.log(this.getStudentName()); // ERROR! 
     }.bind(this)) 
    } 
} 
0

您需要在forEach通過this參考。

array.forEach(function(i, val) { 
    console.log(i, val); 
    console.log(this.getStudentName()); // Now Works! 
}, this); 
相關問題