javascript - "this"的绑定(bind)

标签 javascript binding this

我正在学习如何在 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/

相关文章:

jquery - "this"如何引用JQuery中的DOM元素

javascript - 类似的文件名 ajax

c# - 如何将 ContextMenuStrip 添加到 ToolStripMenuItem

java - GWT 问题,GWT.create(SomeClass.class) 抛出异常

JavaScript、构造函数和 "this"

Angular:为组件字段提供对服务功能的引用并从未按预期工作的模板调用它

identicon 的 Javascript 代码

javascript - 覆盖 qx.core.Object#bind

javascript - 使用 Mocha 和 Chai 捕获超出范围的错误

绑定(bind) Ember TextField 中的计算属性