Explain the use of 'this' keyword in JavaScript

Instruction: Describe how the 'this' keyword works in different contexts within JavaScript.

Context: This question evaluates the candidate's understanding of the context-sensitive nature of the 'this' keyword, a core concept in JavaScript object-oriented programming.

Official answer available

Preview the opening of the answer, then unlock the full walkthrough.

Firstly, in the global execution context, outside of any function, 'this' refers to the global object. In a browser, that's usually the window object. This means that when you're operating in the global scope, this essentially gives you access to the global environment, which can be both powerful and potentially hazardous if not used judiciously.

Moving to function contexts, 'this' behaves differently depending on how the function is called. In a regular function call, this refers to the global object in non-strict mode, and undefined in strict mode ('use strict';). This can be somewhat counterintuitive initially, but it underscores the importance of understanding execution context and why using 'strict mode' can help avoid unintended global variable manipulation....

Related Questions