0

I'm new to Javascript, just a question on 'this' when using anonymous function expression.

const testFunction = function () {
   this.xxx = xxx;
};

later I call it as:

testFunction()

and there will be an error, because we can't use 'this' in this case,

but isn't that 'this' refer to the window object?

unclexo
  • 2,856
  • 2
  • 13
  • 20

1 Answers1

0

If your JavaScript is running in a web browser, under default circumstances, then this will be the window object.

const testFunction = function() {
  console.log(this === window);
};

testFunction();

If strict mode is enabled, then it will not.

Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined:

"use strict";
const testFunction = function() {
  console.log(this === window);
};

testFunction();
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205