I have 2 blocks of code, one that does not work, and one that works because I assign that = this and use that in my function instead of this. Can someone help me understand why this is so. It would help to know how one should think of accessing variables in functions in objects in JavaScript, and the nature of "this", if I am saying that right (if not, please enlighten me). Thank you!
var add = function (x, y) {
return x + y;
}
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
myObject.double2 = function () {
// var that = this;
var helper = function () {
this.value = add(this.value, this.value)
};
helper();
};
myObject.increment(100);
document.writeln(myObject.value); // Prints 100
myObject.double2();
document.writeln('<BR/>'); // Prints <BR/>
document.writeln(myObject.value); // Prints 100, **FAILS**
And the modified code:
var add = function (x, y) {
return x + y;
}
var myObject = {
value: 0,
increment: function (inc) {
this.value += typeof inc === 'number' ? inc : 1;
}
};
myObject.double2 = function () {
var that = this;
var helper = function () {
that.value = add(that.value, that.value)
};
helper();
};
myObject.increment(100);
document.writeln(myObject.value); // Prints 100
myObject.double2();
document.writeln('<BR/>'); // Prints <BR/>
document.writeln(myObject.value); // Prints 200 - **NOW IT WORKS**
thisrefers to the local execution context. (I am 100% sure someone else can word that better then me.) Yourthatvariable is a closure, that captures the value of thethisso that you can reference it from inside the function call, whenever it happens, at some point in the future.