buxlabs / amd-to-es6

convert amd to es
MIT License
35 stars 17 forks source link

top level this and undefined #111

Open dazinator opened 6 years ago

dazinator commented 6 years ago

Hello! For background detail see: https://github.com/rollup/rollup/issues/2523

Given an AMD module with a top level this for example: var self = this when this is converted to an ES6 module, it should be transpiled var self = window because as per: http://exploringjs.com/es6/ch_modules.html#_browsers-scripts-versus-modules a top level this equates to window but in the ES6 world a top level this = undefined. At the moment, after the conversion to ES6 the top level this is currently having its value changed from window to undefined breaking scripts..

emilos commented 6 years ago

hey @dazinator thanks for the bug report! I'll try to investigate soon. You could speed things up a bit by providing a failing spec (ideally expected input/output).

dazinator commented 6 years ago

Hi @emilos No biggie. So given this AMD module as input:

define(function () {   
    var self = this;
    self.foo = function () {      
    };
    self.foo();
    return self;
});

Here is the code after the conversion to es6 modules:

var self = undefined;
self.foo = function () {
};
self.foo();

Note the problem is, in the AMD world, the this is interpreted as referring to the current Window object so the AMD code works. However in es6 modules world, the this takes on a different meaning, it's interpreted as "undefined".

So when this AMD code is converted to ES6 modules it breaks.

This hasn't been too critical because I just changed the AMD modules where this was an issue to avoid using this which is actually a fix as they shouldnt have needed to refer to the window in my case anyway, i.e I now use this:

define(function () {   
    var self = {};
    self.foo = function () {      
    };    
    return self;
});

and this avoids the problem. Thought i'd leave this issue open though in case you wanted to fix it or in case someone else stumbles accross it.