Search code examples
javascriptjquerycoding-stylethisreadability

Keep "this" in a variable and replace all "this" with this variable?


Context

When I use jQuery, I often need to keep this in a variable:

var obj = {
    myVar: null,
    myFunction1: function() { ... },
    myFunction2: function() {
        this.myVar = "blabla";
        this.myFunction1();

        var ctx = this;
        $('xxx').click(function () {
            ctx.myFunction1();
        });
    }
}

In this case, I replace all this with my variable:

var obj = {
    myVar: null,
    myFunction1: function() { ... },
    myFunction2: function() {
        var ctx = this;

        ctx.myVar = "blabla";
        ctx.myFunction1();

        $('xxx').click(function () {
            ctx.myFunction1();
        });

        //etc. I do it for all "this" even if I have 15 "this"...
    }
}

Questions

  • Is it good practice to keep this in a variable? Is there another way?
  • Is it good practice to replace all this with the variable?

Solution

  • Is there another way?

    You can use $.proxy [docs]:

    $('xxx').click($.proxy(function () {
        this.myFunction1();
    }, this));
    

    which obviously overwrites this inside the event handler, so you don't have access to the element through this.

    You can also pass this as event data [docs]:

    $('xxx').click({ctx: this}, function (event) {
        event.data.ctx.myFunction1();
    });
    

    Do whatever you find most readable. I personally just assign var self = this; and use self inside nested functions and this everywhere else.