1

Possible Duplicate:
Can I get the name of the currently running function in javascript?

I want to get the function name from function itself.

Javascript:

Cube : {
    profile : {
        edit : function(){
            // Get function Path Cube.edit Here
            alert(arguments.callee.name); // Not Working
        }
    }
}
Community
  • 1
  • 1
Javed Akhtar
  • 257
  • 1
  • 3
  • 8
  • You could just name your function: `edit: function edit() { ... }` – elclanrs Dec 07 '12 at 07:21
  • @Osiris I goes through this question. but i didn't get my answer. `alert(arguments.callee.name);` not working for above example of code. – Javed Akhtar Dec 07 '12 at 07:23
  • @elclanrs: That creates [two functions](http://blog.niftysnippets.org/2010/09/double-take.html) on IE8 and earlier. – T.J. Crowder Dec 07 '12 at 07:23
  • @elclanrs I edit my code in Question. Please take look. Now i want to get profile.edit() – Javed Akhtar Dec 07 '12 at 07:26
  • 2
    @JavedAkhtar: Changing the code just adding a further object layer is pointless, it doesn't change the question at all, just makes the existing answers look weird until they're edited. – T.J. Crowder Dec 07 '12 at 07:29

1 Answers1

8

The function in your code snippet has no name, it's anonymous. The property it's assigned to on profile has a name (edit), but the function does not. No, there is no way to get edit or profile.edit or Cube.profile.edit from the function object.

You can give the function a name:

Cube : {

   profile: {
       edit : function edit(){

         alert(arguments.callee.name);

       }
   }
}

...but that's using a named function expression which will create two separate function objects on IE8 and earlier.

You can also do this:

Cube : {

   profile: {
       edit : Cube_profile_edit
    }
}
// ...

function Cube_profile_edit(){

    alert(arguments.callee.name);
}

However, in all of the above, two problems:

  1. You're using arguments.callee which is both very slow on a lot of browsers, and not valid in strict mode.

  2. The name property of function objects is non-standard, which is why this answer talks about possibly having to parse the result of Function#toString. The problem is, Function#toString is also non-standard (but fairly broadly supported, except on mobile browsers).

You could avoid that second problem by searching through the Cube object graph for the property that refers to the function, but that would still require using arguments.callee (unless you give the function a real name and then use that real name when searching to find the property path that leads to it).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875