getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
177.9k stars 33.39k forks source link

'this' value in Function Execution Context is related to Strict Mode #1766

Closed young-trigold closed 2 years ago

young-trigold commented 2 years ago

Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line).


Please type "I already searched for this issue": I already searched for this issue

Edition: 2nd

Book Title: get started

Chapter: 3

Section Title: this keyword

Question: I think this section misses a subtle but fatal part: strict mode.

"this" value in Standard Function (not arrow function) Execution Context is related to Strict Mode.

this value in a function directly invoked in strict mode is undefined, if not, global object.

The code sample:

var log = console.log;

var thisValue1 = (function getThisInStrict() {
  'use strict';
  return this;
})();

var thisValue2 = (function getThis() {
  return this;
})();

log(thisValue1 === thisValue2);
// -> false

I hope this section can add some materials on arrow function, execution context, Function.prototype.call().

hopefully helpful.

getify commented 2 years ago

Since this program is not in strict mode (see Chapter 1, "Strictly Speaking"), context-aware functions that are called without any context specified default the context to the global object (window in the browser).