简体   繁体   中英

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

I've run into the problem where I need to pass an object's method as a callback, and that method uses this . Obviously this can't work because when invoked as a callback (not through the owning object) this will point to the global object.

I read about solutions to this problem and am wondering what the best or most common one is.

Currently, my 'class' looks like this:

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

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

Options A - Change the class to look like this:

function MyClass(value) {
    this.value = value;

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

The advantage - simple. But the disadvantage is that alertValue will be copied on every instantiation, which is the reason why we usually put methods on the prototype .

Option B - Use .bind() :

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

I can write a utility method for this:

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

What's the most common approach to solve this problem? What are its pros and cons? Both ways I came up with seem inelegant, is there another way?

I would suggest using bind(). Keep in mind IE <= 8 does not support Function.prototype.bind() so you'd want to use a polyfill. If you have to bind a bunch of methods for a single class, check out Underscore/lodash's _.bindAll() method .

For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM