7

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

rekimizoz
  • 73
  • 1
  • 4

2 Answers2

7

You need to pass this reference in forEach.

array.forEach(function(i, val) {
   console.log(i, val);
   console.log(this.getStudentName()); // Now Works!
}, this);
Nikhil Vartak
  • 5,002
  • 3
  • 26
  • 32
4

'this' changes inside that for loop. You have to force the definition of it. There are several ways to do it. Here is one

   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))
    }
}
ThomasK
  • 300
  • 1
  • 8