1
    this.name = name
}
person.prototype.friends = function(arr){
    var friends = arr.map(function(el){
        return this.name + ' is friend of ' + el
    }.bind(this))
   return friends
  }
let ahmed = new person('Ahmed')
console.log(ahmed.friends(['Mona', 'Khaled']))

I didn't understand why we use bind and when we remove it, the this keyword shows the global object

  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind – epascarello Aug 11 '20 at 17:59
  • 3
    Does this answer your question? [What is the use of the JavaScript 'bind' method?](https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method) – iota Aug 11 '20 at 18:00

3 Answers3

2

The bind() method creates a new function that has the this keyword set to the provided value when called.

Source: MDN

Example:

const x = function() {
  alert(this) // Alerts window
}

const y = function() {
  alert(this)
}.bind('Something else') // Alerts 'Something else'

x()
y()

JSFiddle

Note that this can only be used on function expressions, and not function declarations. For more information, refer to my answer here: https://stackoverflow.com/a/63801906/12984567

GalaxyCat105
  • 2,105
  • 4
  • 12
  • 26
2

As per definition bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

if you remove bind()method then this keyword shows the global object because the way javascript this keyword works. To understand the working of this keyword you can refer here.

To understand the working of bind() method here are the code snippet.

var obj = {
 key: 'xyz',
 display: function(){
   console.log(this.key);
  }
};

obj.display(); // expected output: xyz

const unboundDisplay = obj.display; 
unboundDisplay(); // The function gets invoked at the global scope
// expected output: undefined

const boundDisplay = unboundDisplay.bind(obj);
boundDisplay(); // expected output: xyz

To summarize bind() method is used when we assign this function reference to some other variable

1
person.prototype.friends = function(arr){
    var friends = arr.map(function(el){
        return this.name + ' is friend of ' + el
    }.bind(this))
   return friends
  }

bind makes this available inside function. If you don't have bind in the above code, this will point window, not person. So, without bind, this.name will be undefined.

Philip Moy
  • 341
  • 1
  • 5
  • Without `bind`, `this` would point to `window`, not `function(...){...}`. Otherwise you are right – FZs Aug 11 '20 at 19:17