1

I'm struggling a lot these days with understanding the bind() method, I know that the bind method lets us define the this keyword manually and it creates a copy of the function so we can store it and use it somewhere else everything is ok but there is a case where we use the bind() method that i don't understand which is to solve the this keyword problem as we know the this keyword in a regular function call points to the global object.

let me show you the actual code so you understand what i'm talking about more clearer:

function Person(name){
  this.name=name;
}

var friends=['jane','jack','max']

Person.prototype.myFriends5=function(el){
  // var self=this;
  var arr=friends.map(function(el){
    return this.name +' is friends with '+ el;

  }.bind(this));

  console.log(arr);
};



new Person('john').myFriends5(friends);

focus to the bind() method. I understand that we created a copy of the function but there it's a regular function call and the "this" keyword should points to the global object but No it points to the function, I really don't understand how this works please help me and thanks in advance.

Amine El were
  • 797
  • 2
  • 8
  • 21
  • [My answer](https://stackoverflow.com/a/17711245/633183) in this linked duplicate was recently updated to talk about binding context – Mulan Feb 17 '19 at 00:21
  • Check the MDN docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – arieljuod Feb 17 '19 at 00:22
  • the newer way of doing this is using an arrow function, which has a lexical `this` - `friends.map(el => this.name + ' is friends with ' + el)` – Mulan Feb 17 '19 at 00:22
  • @user633183 i know that but i wanna know the old way too – Amine El were Feb 17 '19 at 00:25

0 Answers0