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()
.
This was a bug in Babel 5 and it's fixed in Babel 6.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With