Function.caller

Function.caller
0

#1

Read section ‘Notes’

there is this code:

var f = stop;
var stack = 'Stack trace:';
while (f) {
  stack += '\n' + f.name;
  f = f.caller;
}

and text:

the loop would never stop.

Why loop never would stop? If function that start whole thing refer to self caller it will be top?

There is at top this text:

If the function f was invoked by the top level code, the value of f.caller is null, otherwise it’s the function that called f.

Vice versa, this code doesn’t work like i expected:

function myFunc() {
  if (myFunc.caller == null) {
    return 'The function was called from the top!';
  } else {
    return 'This function\'s caller was ' + myFunc.caller;
  }
}
console.log(myFunc());

#2

I’m with you on this one. From my console:

f = stop
ƒ stop() { [native code] }
f.caller
null

It seems to work as I’d expect. From my console:

function myFunc() {
  if (myFunc.caller == null) {
    return 'The function was called from the top!';
  } else {
    return 'This function\'s caller was ' + myFunc.caller;
  }
}

f = () => {
    return myFunc();
}

f()
"This function's caller was () => {
    return myFunc();
}"

myFunc()
"The function was called from the top!"

#3

OMG! This post is a year old. I"m dying laughing at myself now.