2

I'd like to know and understand the different between this and that, and when I have to use it. I ready many post and many tutorial but I don't understand yet

this is my class

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        console.log(this.member); // foo
        console.log(that.member); // foo
        return dec() ? that.member : null;
    };
}

New

var myContainer = new Container('foo');
myContainer.service()

Calling myContainer.service() will return 'abc' the first three times it is called. After that, it will return null

Why i have to do var that = this ??

monkeyUser
  • 2,858
  • 6
  • 29
  • 62
  • 1
    Also http://stackoverflow.com/questions/3127429/javascript-this-keyword – elclanrs Apr 14 '14 at 20:40
  • Have you tried it without `that` to see what happens? Might be a good way to learn about what's going on. – CoderDennis Apr 14 '14 at 20:43
  • I dont see the need of `that` in your example. Try `var s = myContainer.service; s()` and see what happens with/without `that`. – phylax Apr 14 '14 at 20:46
  • @CoderDennis yes and it works – monkeyUser Apr 14 '14 at 20:47
  • Similar questions - [self=this](https://stackoverflow.com/questions/337878/var-self-this) and [difference between self and this](https://stackoverflow.com/questions/16875767/difference-between-this-and-self-in-javascript) – RBT Jun 17 '17 at 03:50

1 Answers1

6

this is a variable that gets the context of the current function (which depends on how it was called).

that has no special meaning. It is just a variable to which a value has been assigned.

In this particular case, that is assigned the value that this has while the Container is running, and is used inside the service function (but still has the value that is the context of the call to Container. Since service is a different function, its value of this could be different.


Normally, for this particular design of function, Container would be called as a constructor function (so this would be the instance object of Container) and then service would be called in the context of that instance object so you could use this instead of passing the value around via that. I have no idea why the author of that code chose to use that here.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205