找回“自我”严格模式 JavaScript 中的函数

发布于 2024-10-11 03:19:26 字数 417 浏览 1 评论 0原文

我经常需要在函数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

战皆罪 2024-10-18 03:19:26

你做不到。而且你一开始就不应该这样做,这很神奇,你的函数不应该依赖于它的调用者等。更改你的设计以使其再次工作。

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/

贵在坚持 2024-10-18 03:19:26

值得指出的是,因为我不知道你是否考虑过这一点,如果你只是在对象文字中为函数提供一个名称,你可以这样引用它:

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

但要注意:我认为 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文