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.
The value is
thisis set when a function is called.Setting
thattothispreserves that value for a function defined inside that function (since it would otherwise get a value forthisthat would depend on how it (the inner function) was called.