什么's传递对象的最佳或最常见方式'的方法作为回调

What's the best or most common way to pass an object's method as a callback?

本文关键字:方式 常见 方法 回调 对象 什么 最佳      更新时间:2023-09-26

我遇到了一个问题,需要将对象的方法作为回调传递,而该方法使用this。显然,这是不可行的,因为当作为回调调用(而不是通过所属对象)时,this将指向全局对象。

我读到关于这个问题的解决方案,想知道最好或最常见的解决方案是什么

目前,我的"班级"是这样的:

function MyClass(value) {
    this.value = value;
}
MyClass.prototype.alertValue = function() {
    alert(this.value);
};

选项A-将类更改为如下所示:

function MyClass(value) {
    this.value = value;
    this.alertValue = function() {
        alert(value);
    };
}

优点——简单。但缺点是每次实例化都会复制alertValue,这就是我们通常在prototype上放置方法的原因。

选项B-使用.bind():

callbackReceivingFunction(myObject.alertValue.bind(myObject));

我可以为此编写一个实用方法:

function bind(object, methodName) {
    return object[methodName].bind(object);
}

解决这个问题最常用的方法是什么?它的优点和缺点是什么?我想出的两种方法似乎都很不雅,还有别的方法吗?

我建议使用bind()。请记住IE<=8不支持Function.prototype.bind(),所以您希望使用polyfill。如果必须为单个类绑定一组方法,请查看Underscore/lodash的_.bindAll()方法。

例如:

_.bindAll(myObj, 'alertValue', 'otherMethod', 'anotherMethod')