0

In Douglas Crockford's article, Private Members in Javascript, he uses the variable "that" to refer to "this" for use in the privileged method of the class. I have been using "this.publicMember" in my code and it seems to work right. I would think the only time you would really need to use "that" would be if you are calling the function where the "this" would obviously be different, i.e. calling it from setTimeout. When should I use / not use "that" ?

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 () {
        return dec() ? that.member : null;
    };
}

Versus:

    this.service = function () {
        return dec() ? this.member : null;
    };
wayofthefuture
  • 4,222
  • 6
  • 26
  • 45

2 Answers2

2

He writes in his article:

By convention, we make a private that variable. This is used to make the object available to the private methods.

Then he just uses that everywhere, to avoid issues with unbound functions (like the setTimeout you mentioned) and also to be easily able to switch a "method" between private and privileged. Since the method is already instance-specific anyway (not inherited from the prototype or so), it really doesn't hurt to make it bound and access one more closure variable.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • I started to do that, and worked well for privileged methods, but then when I tried to start changing my objects which had a public prototype.method, it wasn't as easy to get "that" in there. object.prototype.method= function() { var that=this; //doesn't work }. And since the prototype method is the most popular, why don't they need "that" there? – wayofthefuture Aug 25 '15 at 17:25
  • There is no `that` in prototype methods, it makes no sense. Methods on the prototype are shared between all instances, and rely on dynamically bound `this`. – Bergi Aug 25 '15 at 19:16
0

In JS, there are many scenarios in which the value of this won't be the same value of this in an outer block: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work

If you happen to need to use the outer block value of this, then you will use that.

Community
  • 1
  • 1
sahbeewah
  • 2,677
  • 1
  • 10
  • 18