小编rek*_*zoz的帖子

如何在内部调用它,例如在课堂上 forEach?

我倾向于使用 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 oop node.js

6
推荐指数
2
解决办法
6838
查看次数

标签 统计

javascript ×1

node.js ×1

oop ×1