Alisha Sharma
Alisha Sharma

Reputation: 149

Get caller method name in js inside prototype

I have method named my from where I am calling prototype .Inside prototype I want to get Method name from where I am calling . The code below gives all the code of function.

var c = new Object();
c.hello = {}

c.hello.my = function(b) {
  var d = 1,
    c = 1;
  ap('#love').try()
}

x.prototype.try = function(h) {
  console.log(arguments.callee.caller);
}

Above program gives all the code present inside c.hello.my . How can we get the name of function (i.e my). If possible object name as well like **c.hello.my*.

Upvotes: 0

Views: 95

Answers (1)

Ryan Hanekamp
Ryan Hanekamp

Reputation: 618

This has been deprecated to heck and back for both performance and security reasons. Arguments.caller is already non-functional on most engines, and this works at all because it's ultimately calling function.caller, and because you're not in strict mode. This will not work in modules, inside class definitions, and any distance into the future.

I have before been in situations where I thought it would be nice to distinguish who called a function, but I eventually work around it or let it go. If you need the reference to the CURRENT function expression, you can always give it a name:

...
c.hello.my = function NAME_GOES_HERE(b) {
  var d = 1,
    c = 1;
  ap('#love').try()
}
...

When you give a name this way to a function expression ('x=function F()'), the name might or might not be referenced as a variable outside the function, but it's guaranteed to be usable and valid from inside the function.

If a function has a name, you can read function.name to see it. Bear in mind that the textual name isn't nearly as useful in Javascript as it is in other languages. If you want this for debugging purposes, I suggest looking at error.stack. This is non-standard, but has very similar output across browsers.

Upvotes: 1

Related Questions