1

Possible Duplicate:
What does var that = this; mean in javascript?

I often find this assignment in Javascript code:

var that = this;

This is an example:

function Shape(x, y) {
    var that= this;

    this.x = x;
    this.y = y;

    this.toString= function() {
        return 'Shape at ' + that.x + ', ' + that.y;
    };
}

Can you please explain why that is needed?

Please bear in mind I am very familiar with PHP or Java but not with the Javascript object model.

Community
  • 1
  • 1
dan
  • 15,066
  • 19
  • 57
  • 88

4 Answers4

4

It gives the inner function access to the instance that the Shape() method was called on. This type of variable access is called "closure." See here for more detail: https://developer.mozilla.org/en/JavaScript/Guide/Closures

Moishe Lettvin
  • 8,422
  • 1
  • 24
  • 38
4

The value is this is set when a function is called.

Setting that to this preserves that value for a function defined inside that function (since it would otherwise get a value for this that would depend on how it (the inner function) was called.

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

The this in the constructor function refers to the object that will be built from it. However, the this inside it's methods may not refer to that same object anymore.

So we work around that issue by preserving the this into the variable that. That way, we can still refer to the object created without using the this variable.

function Shape(x, y) {
    var that= this;

    this.toString= function() {
        //"this" in here is not the same as "this" out there
        //therefore to use the "this" out there, we preserve it in a variable
    };
}
Joseph
  • 107,072
  • 27
  • 170
  • 214
0
  • Shape is a JavaScript class. It has members toString() and private properties this.x
  • this refers to the current class instance.
  • In order for toString() to realize that it's operating under the 'current class instance', you assign that = this. Since the variable 'that' can be accessed within the scope of toString(). Something this is called a 'me' operator.
JMC
  • 870
  • 5
  • 10
  • Mmh. Strictly speaking there are no classes in JS. `Shape` is a constructor function. And private properties don't exist either, all properties are publicly accessible by any code that has a reference to the object. – Felix Kling May 30 '12 at 21:28