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
胖箭頭功能FTW! 'array.forEach((i,val)=> {' – epascarello