Member-only story
Master These 60 JavaScript Topics for Your Next Interview [PART 2]
11. this, call, apply, and bind
Q1: Explain how `this` behaves in different contexts, including arrow functions.
Answer:
The behavior of this in JavaScript can be quite nuanced, especially when considering different contexts like regular functions, arrow functions, constructors, and various execution environments.
Here’s how this behaves in these contexts:
1. Global Context
In the browser: this points to the window object in non-strict mode, or undefined in strict mode.
In Node.js: this points to global in non-strict mode, or undefined in strict mode.
console.log(this);
// window (in browser) or global (in Node.js) in non-strict mode
2. Regular Functions
- Function Invocation: When a regular function is invoked without any context object, this will either be the global object (in non-strict mode) or undefined (in strict mode).
function regularFunction() {
console.log(this);
}
regularFunction(); // window/global in non-strict, undefined in strict mode
- Method Invocation: When a function is a property of an…