gpt4 book ai didi

javascript - 如何在类里面调用它,例如 forEach?

转载 作者:搜寻专家 更新时间:2023-10-31 23:58:45 24 4
gpt4 key购买 nike

<分区>

我精通 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: Cannot read property 'getStudentName' of undefined

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com