The problem with the context binding: I can not figure out how to bind to this.title - displays undefined .

 function bind(func, context) { return function() { return func.apply(context, arguments); }; } var group = { title: "Наш курс", students: ["Вася", "Петя", "Даша"], showList: function(){ this.students.forEach(function(student) { alert(this.title + ': ' + student); }) } }; var hi = bind(group.showList, group); hi(); 
  • 2
    this.students.forEach(function() {/* */}.bind(this)); not? - Dmitriy Simushev

2 answers 2

For some reason, in neighboring answers, they stubbornly refuse to give an example with context binding . And I will give:

 var group = { title: "Наш курс", students: ["Вася", "Петя", "Даша"], showList: function(){ this.students.forEach(function(student) { alert(this.title + ': ' + student); }.bind(this)); } }; 

And also, you can forget about manual context binding and start using ES6 already. The arrow functions are ideal for this task:

 var group = { title: "Наш курс", students: ["Вася", "Петя", "Даша"], showList: function() { this.students.forEach(student => { alert(this.title + ': ' + student); }); } }; 
  • Thank you very much!!!! I read about the switch functions and just wanted to do this example in the usual way, but I screwed up something ... - aleksei

With the context, everything is fine, as for me, but in the definition of group there is one thing. Try this:

 var group = { title: "Наш курс", students: ["Вася", "Петя", "Даша"], showList: function(){ var title = this.title; this.students.forEach(function(student) { //у вас здесь this.title, но в данном, как раз, контексте, //this.title не определен, потому мы сохраняем его выше //в доступной области видимости alert(title + ': ' + student); }) } }; group.showList();