1

I am using Webpack with babel-loader, and i see this trouble: babel-loader change this agrument in anonymous self-invoking functions to undefined instead this.

In example:

(function (t1, t2) {
})(this, 'test')

Convert to:

(function (t1, t2) {
})(undefined, 'test');
rimlin
  • 397
  • 4
  • 13

1 Answers1

4

Babel assumes that every file is a (ES2015) module. A module's this has the value undefined at runtime. To simulate the correct behavior in environments that don't support modules yet (every environment at this time), Babel replaces every top level this with undefined.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • After further reading, this is the correct answer. For reference, [here is Babel's official explanation](https://github.com/babel/babel.github.io/blob/862b43db93e48762671267034a50c30c00e433e2/docs/faq.md#why-is-this-being-remapped-to-undefined). – Mike Cluck Dec 22 '15 at 16:03
  • 1
    @MikeC: Ah, you found the FAQ, thanks. It seems it's not linked anymore on the actual page. – Felix Kling Dec 22 '15 at 16:06
  • It's not linked because "plugins" should be used instead. However, how to solve this issue for e.g. self-invoking functions? – dude Apr 15 '16 at 10:13
  • @julmot: I don't understand what you mean. What's the issue you want to solve? – Felix Kling Apr 15 '16 at 13:42
  • I would like to know a solution for this issue, not just the background information. Assuming you are using the es2015 preset this issue will occur. How to you prevent babel from replacing `this` with `undefined`? This is especially a problem if you are having a plugin exposure for e.g. AMD or CommonJS and you are passing `this` as a reference for the global environment to a self-invoking function. – dude Apr 15 '16 at 16:35
  • @julmot: Assuming I understand you correctly, why not explicitly pass `window` in that case? I don't think there is a generic solution. But if the general question is "how to reference the global object", I'd use `global` and let my module bundler or another transform take care of substituting it with the right reference. – Felix Kling Apr 15 '16 at 16:41
  • @FelixKling I am open for changes but using `this` and not `window` is the popular way of doing it. In NodeJS there is no `window`, but a `global`. So using `this` will work in both variants, in browsers it will mean `window` and in NodeJS it will mean `global`. [Reference](http://stackoverflow.com/questions/19849136/does-node-js-have-equivalent-to-window-object-in-browser) – dude Apr 15 '16 at 17:56
  • @julmot: not quite. `this` inside a node module does not refer to the global object. It either refers to `module` or `exports` (not sure right now). Besides, I'd argue that using the global object in Node is rather an anti-pattern. – Felix Kling Apr 15 '16 at 21:09