简体   繁体   中英

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?

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);
}

Because you have set the name value in a previous call. this.name is now "fnCallSumm"

function callSumNoName(num1, num2){
    this.name = "myWindow";
    sum.call(this, num1, num2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM