2

I have convert AngularJS application to es6 using webpack and import/export syntax.

Everything works perfect except this keyword.

Since webpack wrap all my code during compilation into iife function (modules), the keyword this gets undefined in functions like:

.controller( …, function() {
 ...
 this.myFunc = function() {

  someFunction().then(function(data) {
   this.someVar = data;
   // this === window
  });

 });

});

In normal angular application without bundling this gets window Object.

I do not want to make a big changes except working with webpack (I have a lot of code places that have that). Is there any way to keep this to point window object in webpack?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Jon Sud
  • 10,211
  • 17
  • 76
  • 174
  • 1
    You can use an arrow function instead: `someFunction().then(data => { this.someVar = data; });` . See [this](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) for details. – Nick Parsons Jun 30 '19 at 11:12
  • No, I don't want to change the entire code. just looking for settings to set this to window. – Jon Sud Jun 30 '19 at 12:16
  • 1
    It is really bad practice to pollute the global namespace with variables. It leads to name collision that creates bugs that are difficult to troubleshoot. – georgeawg Jun 30 '19 at 16:16

1 Answers1

2

Webpack does force code to use "strict mode". The problem comes from the use of ES6 import statements.

From the Docs:

The static import statement is used to import bindings which are exported by another module. Imported modules are in strict mode whether you declare them as such or not.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95