1

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?

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.