Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call this inside for example forEach in class? [duplicate]

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

like image 819
rekimizoz Avatar asked Jul 18 '17 19:07

rekimizoz


2 Answers

You need to pass this reference in forEach.

array.forEach(function(i, val) {
   console.log(i, val);
   console.log(this.getStudentName()); // Now Works!
}, this);
like image 133
Nikhil Vartak Avatar answered Sep 20 '22 18:09

Nikhil Vartak


'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))
    }
}
like image 28
ThomasK Avatar answered Sep 17 '22 18:09

ThomasK