简体   繁体   中英

Transpiled code throws error when masking a parameter with an object variable

We tried to port the following code to 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.

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.

Regardless of whether you should write this kind of code: Is our syntax faulty or is this a bug in Babel?

My understanding is that the definition of cb inside the object should mask the passed parameter. 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?). After that, it should rename the function call inside commit() .

这是Babel 5中的一个错误,它已在Babel 6中修复。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM