简体   繁体   English

JS call():调用函数内的意外“this”上下文

[英]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: 我希望函数sum()中的this.name必须是:

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? 为什么在3个时间它显示从一次的函数调用的名称属性,而不是现在必须提取的窗口对象的name属性?

In callSum the this refers to the global object(winow) so you are actually overwriting window.name that is why you get fnCallSumm twice. callSumthis指的是全局对象(winow),所以你实际上覆盖了window.name ,这就是为什么你得到fnCallSumm两次。

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" this.name现在是“fnCallSumm”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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