rek*_*zoz 6 javascript oop node.js
我倾向于使用 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();
Run Code Online (Sandbox Code Playgroud)
如何从此类中的 forEach 中的函数引用方法?
我有类型错误:
类型错误:无法读取未定义的属性“getStudentName”
您需要this在 中传递引用forEach。
array.forEach(function(i, val) {
console.log(i, val);
console.log(this.getStudentName()); // Now Works!
}, this);
Run Code Online (Sandbox Code Playgroud)
小智 4
'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))
}
}
Run Code Online (Sandbox Code Playgroud)