我遇到了一个问题,我需要将对象的方法作为回调传递,并且该方法使用 this
。显然这是行不通的,因为当作为回调调用时(不是通过所属对象)this
将指向全局对象。
我阅读了有关此问题的解决方案,并且想知道最好或最常见的解决方案是什么。
目前,我的“类(class)”如下所示:
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。如果您必须为单个类绑定(bind)一堆方法,请查看 Underscore/lodash's _.bindAll()
method .
例如:
_.bindAll(myObj, 'alertValue', 'otherMethod', 'anotherMethod')
关于javascript - 将对象的方法作为回调传递的最佳或最常见的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28465564/