[英]Transpiled code throws error when masking a parameter with an object variable
We tried to port the following code to ES6: 我们尝试将以下代码移植到ES6:
function apitest(data) { data.cb(true); } function test(cb) { apitest({cb: function(data) { commit(cb,data); }}); function commit(cb,data) { cb(data); } } test(data => { document.write(data); });
It might look a little confusing, but it does what we expect (return true) and does not throw errors. 它可能看起来有点令人困惑,但它做了我们期望的(返回true)并且不会抛出错误。
However, Babel transpiles it to: 然而,巴贝尔将其转化为:
"use strict"; function apitest(data) { data.cb(true); } function test(_cb) { apitest({ cb: function cb(data) { commit(_cb, data); } }); function commit(_cb, data) { cb(data); } } test(function (data) { document.write(data); }); //# sourceMappingURL=test4.js.map
This code fails since the cb()
called inside commit()
does not have an underscore. 此代码失败,因为在commit()
内部调用的cb()
没有下划线。
Regardless of whether you should write this kind of code: Is our syntax faulty or is this a bug in Babel? 无论你是否应该编写这种代码:我们的语法是错误的还是Babel中的错误?
My understanding is that the definition of cb
inside the object should mask the passed parameter. 我的理解是对象内部的cb
定义应该掩盖传递的参数。 Babel assigns different names to the variable used in the object and in the enclosing function while giving a name to the anonymous function (why would it do that anyway?). Babel为对象和封闭函数中使用的变量分配不同的名称,同时为匿名函数命名(为什么它会这样做呢?)。 After that, it should rename the function call inside commit()
. 之后,它应该重命名commit()
的函数调用。
这是Babel 5中的一个错误,它已在Babel 6中修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.