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

}


Person.prototype.myFriends5 = function(friends) {
  var arr = friends.map(function(el) {
    return this.name + ' is friends with ' + el;
  }.bind(this)); 
  console.log(arr); 
}

var friends = ['Bob', 'Jane', 'Mark']
new Person('John').myFriends5(friends);

Hi, I am having a problem to understand how 'this' keyword works in bind method. So the result of the code above is this "John is friends with Bob","John is friends with Jane","John is friends with Mark". But without .bind(this), the result comes out like this " is friends with Bob"," is friends with Jane"," is friends with Mark". What is the difference with and without .bind(this) in this code?

  • 2
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Wais Kamal Jul 15 '18 at 12:07

2 Answers2

0

You correctly observed that .bind(this) makes "this" available in your code, mainly because you're inside a "map" loop function. Here's an example of how you can make "this" available easily: 'this' in function inside prototype function

Additional: If you look at ES6 classes, they now have a constructor and the class keyword and you don't need to use prototype.

es6 classes docs

excerpt:

class Polygon {
  // ..and an (optional) custom class constructor. If one is
  // not supplied, a default constructor is used instead:
  // constructor() { }
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }

  sayName() {
    ChromeSamples.log('Hi, I am a ', this.name + '.');
  }
}

So if you look at above example, it makes it a bit clearer to look at how the JavaScript class works and it's more like PHP or Java.

Mozilla developer network documentation:

bind

-1

Short answer: with bind you tell the function bound, what the keyword this should be inside of it.

Example for better understanding

var test = function(x) {
  console.log(this.some_important_thing);
  console.log(x);
}

var test_obj = {
  some_important_thing: "Wazaaaa :D"
};

var test2 = test.bind(test_obj, "A"); // new function with prefilled this and parameter
test2();

var test3 = test.bind(test_obj); // new function with prefilled this
test3("B");
SirPilan
  • 3,863
  • 2
  • 9
  • 23