Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 673
chaosflaws Avatar asked Dec 07 '15 15:12

chaosflaws


1 Answers

This was a bug in Babel 5 and it's fixed in Babel 6.

like image 116
kintel Avatar answered Nov 12 '22 11:11

kintel