16

When you are writing complex jQuery/javascript, how do you manage using this without re-defining this variables that were previously defined? Do you have a rule of thumb or a personal preference for naming your this variables (as the nesting gets deeper)?

There are times where I want variables from a higher scope to be available to nested functions/callbacks, but then there are times when I'd like to have a clean slate/scope; is there a good way to call functions/callbacks without having to worry about variable collisions? If so, what technique(s) do you use?


Some super silly test code:

$(document).ready(function() {

    console.warn('start');

    var $this = $(this),

    $dog = $('#dog'),

    billy = function() {

        console.log('BILLY!', 'THIS:', $this, ' | ', 'DOG:', $dog);

        var $this = $(this);

        console.log('BILLY!', 'THIS:', $this, ' | ', 'DOG:', $dog);

    };

             // (#1)
    billy(); // BILLY! THIS: undefined | DOG: jQuery(p#dog)
             // BILLY! THIS: jQuery(Window /demos/this/) | DOG: jQuery(p#dog)

    console.log('THIS:', $this, ' | ', 'DOG:', $dog); // THIS: jQuery(Document /demos/this/) | DOG: jQuery(p#dog)

             // (#2)
    billy(); // BILLY! THIS: undefined | DOG: jQuery(p#dog)
             // BILLY! THIS:  jQuery(Window /demos/this/) | DOG: jQuery(p#dog)

    $('#foo').slideUp(function() {

                                                          // (#3)
        console.log('THIS:', $this, ' | ', 'DOG:', $dog); // BILLY! THIS: undefined | DOG: jQuery(p#dog)

        var $this = $(this); // (#10)

                                                          // (#4)
        console.log('THIS:', $this, ' | ', 'DOG:', $dog); // BILLY! THIS: jQuery(Window /demos/this/) | DOG: jQuery(p#dog)

    });

    $('#clickme').click(function() {

                                                          // (#5)
        console.log('THIS:', $this, ' | ', 'DOG:', $dog); // THIS: undefined | DOG: jQuery(p#dog)

        var $this = $(this);

                                                          // (#6)
        console.log('THIS:', $this, ' | ', 'DOG:', $dog); // THIS: jQuery(button#clickme) | DOG: jQuery(p#dog)

        $('#what').animate({
            opacity : 0.25,
            left    : '+=50',
            height  : 'toggle'
        }, 500, function() {

                                                              // (#7)
            console.log('THIS:', $this, ' | ', 'DOG:', $dog); // THIS: undefined | DOG: jQuery(p#dog)

            var $this = $(this);

                                                              // (#8)
            console.log('THIS:', $this, ' | ', 'DOG:', $dog); // THIS: jQuery(div#what) | DOG: jQuery(p#dog)

        });

    });

             // (#9)
    billy(); // THIS: undefined | DOG: jQuery(p#dog)
             // THIS: jQuery(div#foo) | DOG: jQuery(p#dog)

    console.warn('finish');

});

A full demo page can be found here (jsbin.com).

Note: As you can see, I've "marked" the comments with numbers (#XX) for easy reference.


Observation 1:

Marker (#1)

BILLY! THIS: undefined | DOG: jQuery(p#dog)

Rhetorical question: Why is $this undefined, but $dog is accessible?

Answer: Because the var within that scope is re-defining $this; it's just that I'm trying to log $this before its been defined within that scope.

If I comment out var $this = $(this);, then the marker (#1) returns:

BILLY! THIS: jQuery(Document index2.html) | DOG: jQuery(p#dog)
BILLY! THIS: jQuery(Document index2.html) | DOG: jQuery(p#dog)

The same logic applies to markers (#2), (#3), (#4), (#5), (#6), (#7) and (#8).

Based on this observation (and please correct me if I'm wrong here) I'm assuming that I could put var $this = $(this); at the bottom of the function, and the current scope would know that I want to use the current scope's $this (even though it's not defined yet), and not the parent's $this (even though it IS defined).

POSSIBLE SOLUTION TO AVOIDING $this CONFLICTS:

If one wants to cache $(this) outside/within other closures/functions/callbacks and avoid collisions, then one should use different variable labels like these (for example):

var $$ = $(this);
var $this2 = $(this);
var $t = $(this);
var $that = $(this);

QUESTION:

Is the solution above how you would avoid $this collisions? If not, what's your prefered technique?


Observation 2:

Marker (#9)

THIS: undefined | DOG: jQuery(p#dog)

... $this is undefined for reasons mentioned above, but:

THIS: jQuery(div#foo) | DOG: jQuery(p#dog)

... $this is now $('#foo')!

QUESTION(S):

Exactly why did this happen?

Is it because $this was re-defined via marker (#10)?

(Hmmm, I feel like I need to Google "garbage collection in javascript".)

Again, when writing complex jquery/javascript, what's the best way to avoid this type of variable collision?


I hope these aren't horrible questions. Thanks in advance for taking the time to help me out. :)

4
  • If i had multiple $(this) vars cached, i would name them what they are. for example, if it's a ul, name it $ul, li, $li, etc.
    – Kevin B
    Feb 14, 2013 at 21:30
  • Thanks for tip @KevinB! I've normally used that naming convention when caching elements; I never thought to apply the same thinking for when it comes to caching "this". Thanks!
    – mhulse
    Feb 14, 2013 at 21:58
  • 1
    For example, if I needed to maintain someone else's code and came across an arbitrary $$, I'd be annoyed because I would then then have to search the code to figure out what it references (or log it, etc). If it were instead named $wrapper I would know right away that it was the wrapper.
    – Kevin B
    Feb 14, 2013 at 22:01
  • Ahhhhhh, I totally get that now! Thank you for the clarification. I'm going to experiment with this idea tonight... I've spent all these years using $this or $$, I'm not sure why I never thought to do what you suggest. Great tip!
    – mhulse
    Feb 14, 2013 at 22:16

5 Answers 5

8

You're actually running into variable hoisting issue:

billy = function() {

    console.log('BILLY!', 'THIS:', $this, ' | ', 'DOG:', $dog);

    var $this = $(this);

    console.log('BILLY!', 'THIS:', $this, ' | ', 'DOG:', $dog);

};

is actually interpreted at runtime like this:

billy = function() {

    var $this;

    console.log('BILLY!', 'THIS:', $this, ' | ', 'DOG:', $dog); // $this hasn't been set to anything yet...

    $this = $(this);

    console.log('BILLY!', 'THIS:', $this, ' | ', 'DOG:', $dog);

};

JavaScript hoists variable and function declarations to the top of the scope block so you can reference them before manually declaring them. This gets people into trouble when they reference vars of the same name from outside of the scope block, as you can clearly see in your example.

2
  • 2
    Hoisting. Wow, I'm so glad I asked for help on this one... I never knew that's how JS handled things. Amazing. Thanks so much for the reply and code sample and clarification. +1
    – mhulse
    Feb 14, 2013 at 22:13
  • I really like how you showed how hoisting works. I ran into this issue lately and this clarifies it big time! Feb 18, 2013 at 10:15
4

You've just encountered the joys of scope and JavaScript. One thing a lot of people like to do is, if you need access to the current scope in a callback, define this as self, like so:

var $ = require('jquery')
  , database = require('database')

$.on('click', function(action) {
  var self = this;
  database.connect(function() {
    database.putSync(self.action.button);
  });
});

Note that when 'connect' is called, the scope of "this" is reset to that of the callback and not the click-handler, which is why you've stored your scope in an accessible variable.

3
  • Awesome! I like the idea of using the variable name self (that's one I have not used much). Thanks so much for the tips and code example, it's very helpful. +1
    – mhulse
    Feb 14, 2013 at 22:19
  • 1
    Yeah, you just have to avoid callback hell. If your code is shallow, though, self is great :) callbackhell.com
    – sent1nel
    Feb 15, 2013 at 14:39
  • 1
    For some reason I missed your link to callbackhell.com! I did not realize I could name my inline anon functions! Short read but packed with useful tips. +1!
    – mhulse
    Feb 18, 2013 at 20:10
3

The behavior you are seeing when redeclaring var $this in an inner scope is called hoisting. It's one of the reasons why you should always have a single var statement at the start of each scope for any variables you need in that scope -- not that it's necessary, it's just clearer because it does the same thing and the variable names are easier to locate.

As for having to use a variable in deeply nested scopes .. that may be a sign that something is wrong (too much nesting, single responsibility, etc.). If you need to use certain constructs a lot, consider adding them to the scope of an object instead of giving them names that end with 2. At the very least you should give them descriptive names (I usually only use $this = $(this) within a single scope, and that's to avoid having to call $() repeatedly). self is often used to refer to the current object within function definitions inside of its own scope.

var Dog = function (boy, dog) {
    this.boy = boy;
    this.dog = dog;
    this.$clickme = $("#clickme");
}

Dog.prototype.bind = function () {
    var self = this;

    self.$clickme.on('click', function() {
        var $this = $(this);
        console.log('THIS:', $this, ' | ', 'DOG:', self.dog);

        $('#what').animate({
            opacity : 0.25,
            left    : '+=50',
            height  : 'toggle'
        }, 500, function() {
            var $this = $(this);
            console.log('CLICKME:', self.$clickme, ' | ', 'DOG:', self.dog);
        });
    });
}
4
  • Omg, "hoisting" blows my mind. I can't believe I've gone all of these years without knowing about it. I'm reading article now and digesting your detailed reply and awesome code sample. After I play with your code tonight, I may be back with a few questions. Thank you! +1
    – mhulse
    Feb 14, 2013 at 22:09
  • I like this tip, found in the article you linked to: "I strongly recommend that you have exactly one var statement per scope, and that it be at the top. If you force yourself to do this, you will never have hoisting-related confusion. However, doing this can make it hard to keep track of which variables have actually been declared in the current scope. I recommend using JSLint with the onevar option to enforce this." (I'm gonna give that a try).
    – mhulse
    Feb 14, 2013 at 23:44
  • I'm also playing with the "latedef": true option via JSHint.
    – mhulse
    Feb 15, 2013 at 5:33
  • "shadow": false is also very helpful: "This option suppresses warnings about variable shadowing i.e. declaring a variable that had been already declared somewhere in the outer scope."
    – mhulse
    Feb 15, 2013 at 6:01
2

Others already pointed out the hoisting trouble you experienced in your example. Still I think it is worth mentioning the proxy functionality of jQuery.

It comes in super-handy! You don't have to do stuff like var self = this;, which gives you trouble when nesting multiple scopes.

jQuery proxy documentation

With proxy, you can delegate this into your function, which is very useful if you are using object-oriented javascript in combination with jQuery:

$(document).ready(function () { 
  var $dog = $('#dog');
  // without proxy
  $('.billy').click(function () {
      // $(this) refers to the node that has been clicked 
      $(this).css('color', 'green');
  });

  // with proxy
  $('.billy').click($.proxy(function () {
     // $(this) refers to $dog
     $(this).css('backgroundColor', 'red');
  }, $dog));
});

Working example here: jsFiddle jQuery proxy usage

If you really need your this references side-by-side in a function, I suggest keeping them all loaded up in an array, so you don't have to worry about naming them, and you also keep score of your nesting level:

$(document).ready(function () { 
  var thisStack = [];
  thisStack.push($('#dog'));

  $('.billy').click(function () {
    thisStack.push($this);
    // thisStack[0] refers to $('#dog')
    // thisStack[1] refers to $(this)

    ... more code ...

    thisStack.pop(); // get rid of $(this), leaving scope
  });
});
2
  • 2
    Awesome info! Thanks Justus, I was wondering if $.proxy would be useful in this situation. Thanks so much for the details/clarification/example on that. Also, it's really cool reading your take on using [], that's a great technique! I never would have thought of that. :) +1! Much appreciated!!!
    – mhulse
    Feb 18, 2013 at 11:34
  • And $.proxy is now integrated on jQuery event-handlers, as @Zipp showed in his answer, so you don't have to wrap those functions with the proxy method. Feb 18, 2013 at 14:05
1

As above said. One popular way is to assign variable self to 'this' Another way is to send the scope you want the function to be in as a last parameter:

this.on('change', function() {
 //this is now the scope outside the callback function.
}, this)
3
  • Whoa, that's cool! I did realize that could be done. Makes total sense now that you point it out. Thank you for the tip twibakish! +1! :)
    – mhulse
    Feb 14, 2013 at 22:06
  • Would jQuery's $.proxy also do the same thing? If so, is there an advantage to using one example over the other? I'm still trying to grasp $.proxy so maybe it's not the same thing (it looks similar to what your example is doing though). Thanks again!
    – mhulse
    Feb 14, 2013 at 23:54
  • 1
    It looks like they made the proxy-functionality usable without the need to specify it. If you need to grasp the concept of proxy, see my answer. Feb 18, 2013 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.