[英]Hi, I don't understand how 'this' keyword in bind method works in this code
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. 嗨,我在理解'this'关键字如何在bind方法中工作时遇到问题。 So the result of the code above is this "John is friends with Bob","John is friends with Jane","John is friends with Mark". 因此,以上代码的结果是“ John是Bob的朋友”,“ John是Jane的朋友”,“ John是Mark的朋友”。 But without .bind(this), the result comes out like this " is friends with Bob"," is friends with Jane"," is friends with Mark". 但是没有.bind(this),结果出来的结果是“与鲍勃是朋友”,“与简是朋友”,“与马克是朋友”。 What is the difference with and without .bind(this) in this code? 这段代码中有和没有.bind(this)有什么区别?
You correctly observed that .bind(this) makes "this" available in your code, mainly because you're inside a "map" loop function. 您正确地观察到.bind(this)在代码中使“ this”可用,主要是因为您位于“ map”循环函数中。 Here's an example of how you can make "this" available easily: 'this' in function inside prototype function 这是一个如何使“ this”易于使用的示例: 原型函数中的函数“ this”
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类,它们现在有一个构造函数和class
关键字,您不需要使用prototype
。
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. 因此,如果您看一下上面的示例,那么可以更清楚地了解JavaScript类的工作方式,它更像是PHP或Java。
Mozilla developer network documentation: Mozilla开发人员网络文档:
Short answer: with bind
you tell the function bound, what the keyword this
should be inside of it. 简短的答案:使用bind
可以告诉函数bound, this
应该在其中包含什么关键字。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.