Search code examples
javascriptwindowthiscall

JS call(): Unexpected "this" context within function being called


Here is my experimental script:

window.name = 'myWindow';

function sum(num1, num2){
    console.log('context name: '+this.name+', caller: '+arguments.callee.caller.name);
}

function callSumNoName(num1, num2){
    sum.call(this, num1, num2);
}

function callSum(num1, num2){
    this.name = 'fnCallSumm';
    sum.call(this, num1, num2);
}

console.log(callSumNoName()); // no property name in the function
console.log(callSum());       // the property name is 'fnCallSumm'
console.log(callSumNoName()); // no property name in the function

I expected that this.name within function sum() must be:

myWindow
fnCallSumm
myWindow

...but in reality they are:

myWindow
fnCallSumm
fnCallSumm

What does it mean?! Why in the 3-th time it shows the name property of the function caller from previous time, not the name property of the window object that must be extracted now?


Solution

  • In callSum the this refers to the global object(winow) so you are actually overwriting window.name that is why you get fnCallSumm twice.

    function callSum(num1, num2){
        this.name = 'fnCallSumm';// equivalent to `window.name = 'fnCallSumm';`
        sum.call(this, num1, num2);
    }