新ECMA5 Javascript标准中的arguments.callee.name替代 [英] argument.callee.name alternative in the new ECMA5 Javascript Standard

查看:80
本文介绍了新ECMA5 Javascript标准中的arguments.callee.name替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将一些旧代码移植到严格模式,ECMA5标准中的arguments.callee和类似arguments.caller等的替代方案是什么?

I'm working on porting some old code to 'strict mode', what are the alternatives to the argument.callee and similar argument.caller etc in the ECMA5 standard?

添加的信息:我没有指定为什么需要参数。呼叫者/被叫者。

ADDED INFO: I did not specify why I need the argument.caller/callee.

我的代码m移植使用

assert.ok(elemNode, arguments.callee.name + ": Entity - " + entityId + " has been found");

如果是简单的递归,我可以使用函数name(){... function().. },但是我似乎找不到使用上面的代码的方法。

If it were simple recursion I could use function name(){ ... function() ... }, but I can't seem to find what to do with the above code.

推荐答案

从ECMAScript 3开始,您可以具有命名函数表达式。在此之前,函数表达式是匿名的,这使得 arguments.callee 是必需的。命名函数表达式使它变得不必要。因此,这是推荐的替代方法。

Starting with ECMAScript 3, you can have named function expressions. Prior to that function expressions were anonymous, which made arguments.callee necessary. Named function expressions made it unnecessary. So that's the recommended alternative.

请参见被呼叫者的MDN文档

[1,2,3,4,5].map(function factorial (n) {
    return !(n > 1) ? 1 : factorial(n-1)*n;
});



命名函数的优点(来自MDN文档):




  • 可以从您的代码内部像调用其他函数一样

  • 它不会污染名称空间

  • 此值不变

  • 性能更高(访问参数对象很昂贵)

  • The benefits of named functions (from the MDN docs):

    • the function can be called like any other from inside your code
    • it does not pollute the namespace
    • the value of this does not change
    • it's more performant (accessing the arguments object is expensive)
    • 这篇关于新ECMA5 Javascript标准中的arguments.callee.name替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆