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?
Asked
Active
Viewed 263 times
4
-
1related: http://stackoverflow.com/questions/7234282/what-is-the-reason-for-var-this-this?rq=1 – Niko May 28 '13 at 14:26
-
Take the code, and try to substitute `this` for `that` where used, and you'll see that it likely won't work. – May 28 '13 at 14:26
-
http://stackoverflow.com/a/4886696/1651233 – BobTheBuilder May 28 '13 at 14:26
-
Thanks everyone. Not sure why the previously asked question didn't show up in my initial search for an answer to this :/ – justclaire May 28 '13 at 14:40
3 Answers
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,858
- 6
- 40
- 61
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,816
- 2
- 32
- 40
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.

MobA11y
- 18,425
- 3
- 49
- 76