Questions
What is the `this` keyword and how does it work in JavaScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new component that has a method that needs to access a property of the component.
You are not sure how to use the this keyword to access the property.
The Challenge
Explain what the this keyword is in JavaScript and how its value is determined. What are the different ways to set the value of this, and what are the common pitfalls to avoid?
A junior engineer might be confused by the `this` keyword. They might not be aware of the different ways to set its value, or they might not know how to use it correctly in different contexts.
A senior engineer would have a deep understanding of the `this` keyword. They would be able to explain how its value is determined and would have a clear plan for how to use it correctly in different contexts.
Step 1: Understand How the Value of this is Determined
The value of the this keyword is determined by how a function is called.
| How the function is called | Value of this |
|---|---|
| In the global context | The global object (window in a browser, global in Node.js). |
| As a method of an object | The object that the method was called on. |
With new | A new object that is created by the new operator. |
With call, apply, or bind | The object that is passed as the first argument to call, apply, or bind. |
| As an event listener | The element that the event was fired on. |
| As an arrow function | The value of this from the enclosing lexical scope. |
Step 2: Code Examples
Here are some code examples that show how the value of this is determined:
As a method of an object:
const myObject = {
myMethod() {
console.log(this);
}
};
myObject.myMethod(); // myObjectWith call, apply, or bind:
function myFunction() {
console.log(this);
}
myFunction.call({ a: 1 }); // { a: 1 }As an arrow function:
const myObject = {
myMethod() {
const myArrowFunction = () => {
console.log(this);
};
myArrowFunction();
}
};
myObject.myMethod(); // myObject Practice Question
What will be logged to the console?