I am trying to understand how the call() method works. I have the following snippet of code that I executed in the Firebug Javascript console.
Code:
var window = {num1: 10, num2: 20};
var o = {num1: 20, num2: 30};
var sum = function(num1, num2) {
return this.num1 + this.num2;
};
console.log(sum.call(o)); // 50
console.log(sum.call(window)); // 30
console.log(sum.call(this)); // 30
Output:
50
NaN
NaN
I expected the output to be 50 and 30 respectively. Why does call() return a NaN when window/this object is passed as an execution context?
windowis a reserved word in a browser. You can't override or hide it with a variable.thisis referring to the global namespace, which apparently doesn't have a num1 or num2 member in it.(function() { var window = {}; console.log(window) }());- but of course you can't overwrite it completely and you can still access it in the closure by doing something liketop.windowwindowand assumed that if I overridewindowand add variables to it, it would be part of the global scope. The clarification helps :)