Search code examples
javascriptfunctionargumentsstrict-mode

Retrieve "self" function in the strict-mode JavaScript


I often need in a function f to retrieve a name of the method that points to f. For example. Let's say we have a getMethodName(obj, methodFunction) function that uses foreach on obj to find a property that is a link to methodFunction:

obj = { 
    foo : function() {
        var myName = getMethodName(obj, arguments.callee); // "foo"
    }
}

How do I do this in strict mode where arguments.callee is deprecated?


Solution

  • You can't do it. And you shouldn't do it in the first place, this is magic, your function should not depend on its caller etc. Change your design in order to make it work again.

    arguments.callee and .caller have not only been removed because of being bad style, but also because they defeat optimization. Namely inlining, you can't inline something if you depend on the caller, nor on the function, since the code might have just put somewhere without the function around it.

    Read: http://whereswalden.com/2010/09/08/new-es5-strict-mode-support-now-with-poison-pills/