18

I have few javascript that has used the keyword "that" extensively. I see a lot of posts talking about the javascript keyword "this".

I wanted to understand the meaning of this key word in javascript context and it's visibility/scope.

Something like

that.someFunctionaName(someParameter)

What does it mean?

I understand the keyword "this" always points to the owner of the current object.

Ayusman
  • 8,509
  • 21
  • 79
  • 132
  • 1
    that is not a keyword, but a simple variable name – feeela Feb 14 '13 at 09:41
  • 1
    `that` is not a keyword, it's a simple variable. For `this`, see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this – Bergi Feb 14 '13 at 09:41
  • 4
    Please use the search function before asking a question, next time. – Cerbrus Feb 14 '13 at 09:42
  • 1
    The concept behind this is, to use "that" as function wide global variable when you use closures to access the scope of the object. It's not a good way to do this in object oriented programming but in Javascript it's a quick way to solve such problems. – Johni Feb 14 '13 at 09:44
  • A great explanation on mysterious this behavior based on context [here](https://zellwk.com/blog/this/) – RBT Oct 23 '17 at 10:59

1 Answers1

30

that is not a keyword in JavaScript. I suspect the code that you have is using something in the class to define an instance of itself. For example:

function myClass()
{
    var that = this;
}

By doing this, you can ensure you're referencing the object, and not another element. For example, consider the following sample:

function myClass()
{
    var that = this;
    $('.myele').click(function() {  

        // 'this' refers to the element that was clicked.
        // 'that' still refers to the myClass() object.
    });
}
BenM
  • 52,573
  • 26
  • 113
  • 168
  • 4
    Another fairly commonly used variable for this is `self`, following the same logic. – Mitch Satchwell Feb 14 '13 at 09:43
  • @BenM thanks for the info. Yes it somewhat makes sense, I will do some more reading to understand the aspects of using such reference. And you are right, I got the "that = this" in my js code base after you suggested it. It more clear to me now. – Ayusman Feb 14 '13 at 23:20
  • hi @BenM my `that` looks like this `var that = {};` is it the same as `var that = this;` – Ker p pag Oct 01 '14 at 02:26
  • No. `that { };` assigns an empty object to `that`. – BenM Oct 01 '14 at 07:40