嗨,我不明白bind方法中的'this'关键字在这段代码中如何工作

时间:2018-07-15 12:03:51

标签: javascript

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);

嗨,我在理解'this'关键字如何在bind方法中工作时遇到问题。 因此,以上代码的结果是“ John是Bob的朋友”,“ John是Jane的朋友”,“ John是Mark的朋友”。  但是没有.bind(this),结果出来的结果是“与鲍勃是朋友”,“与简是朋友”,“与马克是朋友”。 这段代码中有和没有.bind(this)有什么区别?

2 个答案:

答案 0 :(得分:0)

您正确地观察到.bind(this)在代码中使“ this”可用,主要是因为您位于“ map”循环函数中。这是一个如何使“ this”易于使用的示例:'this' in function inside prototype function

其他:如果您查看ES6类,它们现在有一个构造函数和class关键字,您无需使用prototype

es6 classes docs

节选:

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 + '.');
  }
}

因此,如果您看一下上面的示例,那么可以更清楚地了解JavaScript类的工作方式,并且更像PHP或Java。

Mozilla开发人员网络文档:

bind

答案 1 :(得分:-1)

简短的回答:使用bind告诉函数绑定,关键字this应该在其中。

示例以便更好地理解

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");

相关问题