I recently have started reading "JavaScript: good parts" and quoting one of the examples which I couldn't understand. I added a test function to the original example:
var add = function(a,b) {
return a+b;
};
var myObject = {
val: 0,
increment: function(inc) {
this.val += typeof inc == 'number' ? inc : 1;
}
};
myObject.increment(12);
myObject.increment();
// till this line, the val is equal to 13
// function invocation
myObject.double = function() {
var that = this;
// inner function #1
var helper = function() {
that.val = add(that.val, that.val);
};
// inner function #2
var test = function(){
this.val = add(this.val, this.val);
};
helper(); // the val is equal to 26
// test(); // the val is equal to 13
};
When I use that (var that = this) I am referring to myObject's field, val. Also when I use this in my test function, I am referring to the same field in the same object, but the answer is different. any explanation would be appreciated.