Why undefined?

There is a problem. Why kvoo in alegrete undefined? Caused by because in the right context using the call:
https://jsfiddle.net/CitizenOne/ha49evee/20/
But with bind works:
https://jsfiddle.net/CitizenOne/ha49evee/21/
June 10th 19 at 16:11
3 answers
June 10th 19 at 16:13
Solution
The handler function that you pass to forEachis executed in the context of the current element of the array.
If the method forEach() was passed thisArg, when calling the callback it will be used as the this value. Otherwise, as this value will be used the value undefined. Ultimately, the value of the observable by callback is determined according to the usual rules for determining the this seen by a function.
Here is a quote from the directory
If the method forEach() was passed thisArg, when calling the callback it will be used as the this value. Otherwise, as this value will be used the value undefined. Ultimately, the value of the observable by callback is determined according to the usual rules for determining the this seen by a function.

That is the context not the current element. - maxie.Mo commented on June 10th 19 at 16:16
Yes, I mean stupid, and the handler function establishes its importance this, that is window. Solution: use the arrow functions to save a context in a variable, pass the context in the forEach by using the keyword. Arrow functions are the simplest option:

this.students.forEach(student => alert(this.title + ': '+ student))
- gustave_Kertzmann52 commented on June 10th 19 at 16:19
June 10th 19 at 16:15
//'use strict';

let group = {
 title: "Our course",
 students: ["John", "Peter", "Dora"],

 showList: function() {
 this.students.forEach(function(student) {
 alert(group.title + ': '+ student); // will error
})
}
}


group.showList.call(group);
=))).Read the context of this - maxie.Mo commented on June 10th 19 at 16:18
Well , so you prsoto I took and this was removed. In your code there is no need to call. Without it work. - gustave_Kertzmann52 commented on June 10th 19 at 16:21
June 10th 19 at 16:17
Use console.log();
In your case, if you set console.log(this) right after showList: function() { ...
in the console you will see the object. Accordingly, try this:
group.students.forEach(function(student) {
 alert(group.title + ': '+ student); 
 })
Well, you prsoto I took and this was removed. In your code there is no need to call. Without it work. And I need this. The strange thing is that the bind all works. - maxie.Mo commented on June 10th 19 at 16:20

Find more questions by tags JavaScript