What is “that” in Javascript?

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

You might have seen the use of “that” in Javascript. You may know that “this” points to the object invoker of the function. But what is “that”?

Actually, “that” is not a Javascript keyword. It is just a variable name that someone named as “that”. Why in the world would someone name a variable that?

By convention, many people actually uses “that” in a particular type of situation. Take for example, the following page which has two buttons.

this in Javascript works

this in Javascript works

When one of the button is clicked, it alerts the id of the clicked button. This works and it is a typical use of the “this” keyword.

However, a child function created inside the onclick function would not have access to the “this” object. The following will alert “undefined was clicked” because this is undefined inside the alerter function…

but not when inside another Javascript function

but not when inside another Javascript function

So what programmers do is to save “this” into “that” and pass “that” into the child function …

use of that in Javascript works

use of that in Javascript works?

So that is why “that” is used in Javascript.