简体   繁体   English

使用对象变量屏蔽参数时,透明代码会引发错误

[英]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.

相关问题 运行 Babel 转译代码时需要 JSON 文件引发 Node.js 加载程序错误“错误:找不到模块'example.json'” - require a JSON file throws a Node.js loader error "Error: Cannot find module 'example.json'" when running Babel transpiled code Babel成功地转译了ES6代码(node.js),但是当“ npm start”执行时,它会抛出“ SyntaxError:意外的令牌导入” - Babel transpiled ES6 code (node.js) successfully, but when do “npm start” it throws “SyntaxError: Unexpected token import ” 代码转换时,TypeScript 的接口参数不起作用 - Interface argument of TypeScript is not working when the code is transpiled 为什么类中的私有变量在转译的代码中被视为公共变量 - Why private variable in a class is treated as public in the transpiled code 如何将我的 JSX 代码转换为 JS 对象? - How I can transpiled my JSX code into JS object? 代码执行抛出错误“对象不是函数” - Code execution throws error “object is not a function” 代码抛出字符串而不是错误时发出警告 - Warn when code throws a string instead of an error 未捕获的错误:编译后在Browserify Gulp中找不到模块 - Uncaught Error: Cannot find module in Browserify Gulp when transpiled 将变量设置为undefined时,Microsoft JScript抛出“ variable”是未定义的错误 - Microsoft JScript throws 'variable' is undefined error when setting variable to undefined 编译后的代码给出TypeError:不是构造函数 - Transpiled code gives TypeError:is not a constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM