我精益Node.js和JavaScript。我有示例类:
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:
TypeError:无法读取属性' getStudentName'未定义的
答案 0 :(得分:1)
您需要在this
中传递forEach
引用。
array.forEach(function(i, val) {
console.log(i, val);
console.log(this.getStudentName()); // Now Works!
}, this);
答案 1 :(得分:-1)
'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))
}
}