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
You need to pass this
reference in forEach
.
array.forEach(function(i, val) {
console.log(i, val);
console.log(this.getStudentName()); // Now Works!
}, this);
'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))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With