javascript - 将 JavaScript 的 .bind() 与回调函数集成

标签 javascript bind

所以,下面是一个非常简单的示例,其中我将 that 设置为 this 因此我可以使用 myObj。我将如何集成 Function.prototype.bind,这样我才能了解将来如何使用它?

var myObj = {

        specialFunction: function () {

        },

        anotherSpecialFunction(){

        },

        getAsyncData: function (cb) {
            // an operation
            cb();
        },

        render: function () {
            var that = this;
            this.getAsyncData(function () {
                that.specialFunction();
                that.anotherSpecialFunction();
            });
        }
    };

    myObj.render();

最佳答案

只需在您想要的方法上使用绑定(bind)并指定上下文

render: function () {
    this.getAsyncData(this.specialFunction.bind(this));
}

    render: function () {
        this.getAsyncData(someFunction.bind(this));
        function someFunction() {
            this.specialFunction();
            this.anotherSpecialFunction();
        }
    }

关于javascript - 将 JavaScript 的 .bind() 与回调函数集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19227872/

相关文章:

javascript - 在不更改表格布局的情况下使用javascript隐藏部分表格

javascript - 按下按钮时,如何将用户上传的图像传递到另一个 div?

JavaScript - 在函数回调之间共享值

css - 将 CSS 样式属性绑定(bind)到 JavaFX 中的节点

c++ - 在 sqlite3 语句中绑定(bind) 'unsigned long' (uint64)? C++

javascript - 如何在vuejs2中使用 Controller

javascript - 如何处理 "outside"单击 Dialog (Modal)?

javascript - 如果Object.prototype被修改,如何测试对象是否为 "isEmpty()"?

python-3.x - 如何在消息框中显示网页链接

C++使用转换(绑定(bind))除数