HTML and CSS Reference
In-Depth Information
NaN
The problem can be seen if we add some logging to the code:
> obj = { nums: 10,
add: function(num2) {
console.log('Outer this ' + this)
helper = function(num2) {
console.log('Inner this ' + this)
this.num += num2;
return this.num;
}
return helper(num2);
}
}
If you execute this now, you will see the following output:
> obj.add(20)
Outer this [object Object]
Inner this [object Window]
NaN
Surprisingly the this inside the inner function has reverted from being the object to being
the window . This is considered by most as a bug in the language, but it is a bug that will
not be rectified since it would break legacy code.
The common way to avoid this issue is as follows:
> obj = { num: 10,
add: function(num2) {
var that = this;
helper = function(num2) {
that .num += num2;
return that .num;
}
return helper(num2);
}
}
Search WWH ::




Custom Search