How to call this inside for example forEach in class?

Viewed 8514

I lean Node.js and JavaScript. I have example class:

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();

How can I refer to a method from a function inside a forEach in this class?

I have TypeError:

TypeError: Cannot read property 'getStudentName' of undefined

2 Answers
Related