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.