0

The following example works as expected, and console.log(this) returns methods, variables, etc

function foo() {
  console.log(this);
}

foo();

However, this does not:

export const something = 'anything';

function foo() {
  console.log(this);
}

foo();

In this case, conosle.log(this) is undefined. Why?

Kousha
  • 22,419
  • 30
  • 119
  • 232

2 Answers2

3

I'm guessing you're running your first example without the --experimental-modules flag, but you're running your second example with the flag.

Code in ESM modules is always in strict mode. In strict mode, if you don't do something to set what this is during a call (which you don't with foo();), this within the call gets the value undefined. But in loose mode (sometimes called "sloppy" mode), foo(); sets this to the global object during the call.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • You are right; when I compile it the use of `"use strict"` is doing this. – Kousha May 09 '19 at 07:08
  • How do I then have a context `this` inside a function? I'd like to call my function as `name()` but still have a context `this`; not necessarily the global `this`, but any `this` – Kousha May 09 '19 at 07:08
  • @Kousha - See [this question's answers](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). Basically, you call it as a method on an object (`obj.foo();`) or you use `call` or `apply` (`foo.call(valueForThis, arg1, arg2)` or `foo.apply(valueForThis, [arg1, arg2]);`). – T.J. Crowder May 09 '19 at 07:10
0

If can be helpfull

function foo() {
  console.log(this);
}

// main script 'this'
foo() 

// execute foo with 'this' set to {foo: 'bar'}
foo.bind({ foo: 'bar '})();

// execute foo with 'this' set to the very function 'foo'
foo.bind(foo)();
Andrea Franchini
  • 456
  • 3
  • 12