0

I want to use the property of "caller" for a function which is defined here

It works fine for this style of function declaration

    function g() {
      alert(g.caller.name) // f
}

   function f() {
      alert(f.caller.name) // undefined
      g()
}

f()

JSfiddle for this

But then my function declaration is something like

    g = function() {
      alert(g.caller.name) // expected f, getting undefined
    }


   f = function() {
     alert("calling f")
     alert(f.caller.name) // undefined
     g()
   }

 f()

and I am getting undefined (basically not getting anything)

JSfiddle for this

Is there any way that I can use the caller property without having to rewrite my code? Also, I hope I have not made any mistakes in usage and function declaration since I am quite new to using JS.

Kara
  • 6,115
  • 16
  • 50
  • 57
arvind
  • 117
  • 1
  • 3
  • 11
  • See [JavaScript: var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname) and the [Function `name` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) – Bergi Jun 26 '13 at 10:34

1 Answers1

1

This function...

f = function() {
    g();
};

... does not have a name. It's an anonymous function, assigned to a variable with the identifier f. It will work as is if you make that function a named function expression:

f = function f() {
    g();
};

Note that since that anonymous function is called from the global execution context, it's caller property is null (note that in JSFiddle, it won't be null, it will be whatever function JSFiddle calls to invoke your code).

You have demonstrated one of the differences between function declarations and function expressions. Your first example shows function declarations. They must have an identifier. Your second example uses function expressions. The identifier is optional, and is only in scope within the function itself.

James Allardice
  • 164,175
  • 21
  • 332
  • 312