开发者

Retrieve "self" function in the strict-mode JavaScript

开发者 https://www.devze.com 2023-02-03 20:14 出处:网络
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, method开发者_StackOverflow中文版Function) function that uses foreac

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, method开发者_StackOverflow中文版Function) 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?


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/


It's worth pointing out, since I can't tell if you considered it, that if you simply supply a name to the function in the object literal, you can refer to it that way:

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

But beware: I think IE has a bug in release versions where this will define a function named METHODNAME in the enclosing scope (rather than making it accessible to that function only). By spec, however, this is perfectly kosher and works perfectly fine so long as you use a name not found anywhere in the function itself, or in code passed to eval if the function can call eval.

0

精彩评论

暂无评论...
验证码 换一张
取 消