4

I came across this many times in a new code base that I'm looking at and was wondering is there is any proper reasoning behind it?

justclaire
  • 177
  • 1
  • 2
  • 9

3 Answers3

2

You can use var that = this; is order to keep a reference to current this object, when later this will be pointing to something else.

Example (taken from here):

$('#element').click(function(){
    // this is a reference to the element clicked on

    var that = this;

    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});
Community
  • 1
  • 1
BobTheBuilder
  • 18,283
  • 5
  • 37
  • 60
1

Sometimes the meaning of this in JavaScript changes based on the scope. this inside of a constructor means something different than this inside of a function. Here's a good article about it.

austin
  • 5,778
  • 2
  • 30
  • 39
0

If you want access to "this" outside/inside of the scope of a specific function call where what "this" is may have changed. Just one example I can think of.

ChrisCM
  • 17,786
  • 3
  • 45
  • 72