我正在学习如何在 JavaScript 中绑定(bind)“this”的值。在下面的示例中,“this”绑定(bind)到 getFriends() 方法而不是“details”对象是否正确,这就是 this.name = ""而不是 this.name = "Joe"的原因?
const details = {
name: 'Joe',
friends: [ 'Bob', 'Alex' ],
getFriends: function() {
this.friends.forEach( function( friend ) {
console.log( this.name + " is friends with " + friend );
} );
}
};
details.getFriends();
// Output:
// is friends with Bob
// is friends with Alex
根据我的研究,“this”不会绑定(bind)父范围中的上一级,对吗?这是使用箭头函数的一个好处,它将“this”绑定(bind)到父作用域。
最佳答案
不,当您以这种方式运行代码时,this
指向全局窗口对象。您可以console.log
this
的值。要测试它,您还可以在窗口上放置一个 my_name
键(不要使用名称,因为它已被窗口使用)。现在,当您运行代码时,您将看到全局:
const details = {
my_name: 'Joe',
friends: [ 'Bob', 'Alex' ],
getFriends: function() {
this.friends.forEach( function( friend ) {
console.log( this.my_name + " is friends with " + friend );
} );
}
};
window.my_name = "What?"
details.getFriends();
仅供引用:forEach
采用第二个值,您可以使用该值指定回调中的 this
。所以这适用于例如:
const details = {
my_name: 'Joe',
friends: [ 'Bob', 'Alex' ],
getFriends: function() {
this.friends.forEach( function( friend ) {
console.log( this.my_name + " is friends with " + friend );
}, this ); //<-- pass this into the forEach
}
};
details.getFriends();
当然,您也可以随时使用箭头函数。
关于javascript - "this"的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56157472/