我倾向于使用 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”
我按照教程创建了一个JavaScript秒表,并尝试将其扩展为使用多个秒表(一个类的多个实例).我遇到的问题是当我试图在时钟滴答作响时显示当前值时我需要对类实例进行硬编码,因为使用"this"不起作用(在我使用console.log的行上).我已经将代码减少到最低限度以尝试理解这方面,并粘贴了我在下面的内容:
function Timer(){
var time1 = null;
var time2 = null;
var timeLoop = null;
function getTime(){
var day = new Date();
return day.getTime();
}
this.start = function(){
time1 = getTime();
timeLoop = setInterval(function(){
time2 = getTime();
console.log(_Timer.duration());
//console.log(this.duration());
},500);
}
this.duration = function(){
return (time1 - time2) / 1000;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为下面的链接描述了我的问题,但我不明白它在这里应用它.问题是由于所有者是this.start而不仅仅是这个,我如何修改代码以使其适用于任何Timer实例?
http://www.quirksmode.org/js/this.html
我已经包含了硬编码值行和不起作用的"this"行.
谢谢,
杰兰特