【问题标题】:Babel transpiler is reassigning arguments to _argumentsBabel 转译器正在将参数重新分配给 _arguments
【发布时间】:2016-02-23 12:19:19
【问题描述】:

为什么在将我的 javascript 从 ES5 转译到 ES2015 时,Babel 会添加以下代码行?

var _arguments = arguments;

这一行打破了我的代码中引用参数的功能......有什么想法吗?

中断的函数只需要一个字符串'word'并将其连接到传入的以下参数:

concatWordsExample: word => {
   let wordAndFirstArg = word + arguments ? arguments[0] : '';
}

函数调用示例:

concatWordsExample('firstword ', 'secondword');
// I expected wordAndFirstArg to be 'firstword secondword'; 

我正在通过 Grunt 使用 Babel v6.0.0

【问题讨论】:

    标签: ecmascript-6 babeljs


    【解决方案1】:

    这里的问题是我在示例中的 ArrowFunction 中使用了“参数”(ES5 语法):

    concatWordsExample: word => {
       let wordAndFirstArg = word + arguments ? arguments[0] : '';
    }
    

    在这种情况下,参数不引用箭头函数的参数,这正是我想要的-“在 ArrowFunction 中对参数、super 或 this 的任何引用都被解析为它们在词法封闭函数。” 因此,我可以重写传统函数,尽管更好的解决方案是简单地使用新的“rest arguments”ES2015 语法,例如:

    concatWordsExample: (word, ...args) => {
       let wordAndFirstArg = word + args ? args[0] : '';
    }
    

    这是来自 Babel 的官方简介:

    ArrowFunction 中对参数、super 或 this 的任何引用都将解析为它们在词法封闭函数中的绑定。即使 ArrowFunction 可能包含对 super 的引用, 步骤 4 中创建的函数对象不会通过执行 MakeMethod 变成方法。引用 super 的 ArrowFunction 总是包含在非ArrowFunction em> 和实现 super 的必要状态可以通过 ArrowFunction 的函数对象捕获的 scope 访问。”

    【讨论】:

    • 请在您的问题中包含第一个代码 sn-p 和周围的函数。它不是很有意义。我还建议将 "This is not correct in ES2015" 替换为 " 在这种情况下的参数不是指箭头函数的参数,这正是我想要的。" 仅从代码我们无法推断出你想要那个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2013-06-04
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多