This, bind, that in the callback of javascript, node.js


If you want to pass the current object to the callback function in any operation (read file, connect database…)

There are three main ways to deal with this in callbacks:

1. Create a normal variable, as you are currently doing

The most common names for the variable are that and self. I prefer that because in the browser there is a global window property called self that I’d rather not shadow.

function edit(req, res) {
    var that = this,

    db.User.findById('ABCD', function(err, user){
        that.foo(user);
    });
};

A good advantage of this approach is that once the code is converted to using that you can add as many inner callbacks as you want and they will all seamlessly work due to lexical scoping.

2. Use the .bind() method to explicitly set the scope.

In newer browsers (and Node.js’s V8 engine) you can use the .bind() method to create a new function that has the correct this

function edit(req, res) {
    db.User.findById('ABCD', (function(err, user){
        this.foo(user);
    }).bind(this));
};

The main advantage of this approach is that you don’t need to restructure a bunch of code or create extraneous functions if all you need to do is control the scope in a single spot.

The disadvantage of this version is that you need to remember to bind all the callbacks you use.

3. If you can’t use .bind or need more fine-grained control of function scope or arguments, use .call() and .apply()

For example, you can use .apply() like this:

function myBind(scope, func){
     return function(){
         return func.apply(scope, arguments);
     };
}

The .call() function is similar but accepts arguments as they are instead of an array like.apply().

Copy from http://stackoverflow.com/questions/7874723/maintaining-the-reference-to-this-in-javascript-when-using-callbacks-and-closu

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s