找回“自我”严格模式 JavaScript 中的函数
我经常需要在函数 f
中检索指向 f
的方法的名称。例如。假设我们有一个 getMethodName(obj, methodFunction)
函数,它在 obj
上使用 foreach
来查找作为 链接的属性methodFunction
:
obj = {
foo : function() {
var myName = getMethodName(obj, arguments.callee); // "foo"
}
}
如何在不推荐使用 arguments.callee
的严格模式中执行此操作?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你做不到。而且你一开始就不应该这样做,这很神奇,你的函数不应该依赖于它的调用者等。更改你的设计以使其再次工作。
arguments.callee
和.caller
被删除不仅是因为它们的风格不好,而且还因为它们无法优化。即内联,如果您依赖于调用者或函数,则无法内联某些内容,因为代码可能只是放置在没有函数周围的地方。阅读:http:// whereswalden.com/2010/09/08/new-es5-strict-mode-support-now-with-poison-pills/
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/
值得指出的是,因为我不知道你是否考虑过这一点,如果你只是在对象文字中为函数提供一个名称,你可以这样引用它:
但要注意:我认为 IE 在发布时有一个错误版本中,这将在封闭范围内定义一个名为
METHODNAME
的函数(而不是使其仅可由该函数访问)。然而,根据规范,这是完全合规的,只要您使用在函数本身中找不到的名称,或者在传递给eval
的代码中(如果函数可以调用eval),它就可以完美地工作。
。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:
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 toeval
if the function can calleval
.