Home >Web Front-end >JS Tutorial >Mastering the this Keyword in JavaScript: Never to look back again
JavaScript’s this keyword is a fundamental concept that often puzzles both beginners and seasoned developers alike. Its dynamic nature can lead to unexpected behaviors if not thoroughly understood. This comprehensive guide aims to demystify this, exploring its various contexts, nuances, and best practices, complete with illustrative examples and challenging problems to solidify your understanding.
In JavaScript, this is a keyword that refers to the object from which the current code is being executed. Unlike some other programming languages where this is statically bound, JavaScript’s this is dynamically determined based on how a function is called.
When not inside any function, this refers to the global object.
Example
console.log(this === window); // true (in browser) console.log(this === global); // true (in Node.js)
Note: In strict mode ('use strict';), this in the global context remains the global object.
In regular functions, this is determined by how the function is called.
Example:
function showThis() { console.log(this); } showThis(); // Window object (in browser) or global (in Node.js)
Example
const person = { name: 'Alice', greet: function() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice"
We can use call, apply, or bind to explicitly set this.
function greet() { console.log(`Hello, I'm ${this.name}`); } const person = { name: 'Bob' }; greet.call(person); // "Hello, I'm Bob"
Arrow functions have a lexical this, meaning they inherit this from the surrounding scope at the time of their creation.
Example
const person = { name: 'Charlie', greet: () => { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm undefined" (or global name if defined)
Explanation: Since arrow functions do not have their own this, this refers to the global object, not the person object.
Correct Usage with Arrow Functions:
const person = { name: 'Dana', greet: function() { const inner = () => { console.log(`Hello, I'm ${this.name}`); }; inner(); } }; person.greet(); // "Hello, I'm Dana"
Challenging Aspect: If a method is assigned to a variable and called, this may lose its intended context.
Example
const calculator = { value: 0, add: function(num) { this.value += num; return this.value; } }; console.log(calculator.add(5)); // 5 console.log(calculator.add(10)); // 15 const addFunction = calculator.add; console.log(addFunction(5)); // NaN (in non-strict mode, this.value is undefined + 5)
When a function is used as a constructor with the new keyword, this refers to the newly created instance.
console.log(this === window); // true (in browser) console.log(this === global); // true (in Node.js)
Important Notes:
• If new is not used, this might refer to the global object or be undefined in strict mode.
• Constructors typically capitalize the first letter to distinguish them from regular functions.
In event handlers, this refers to the element that received the event.
Example
function showThis() { console.log(this); } showThis(); // Window object (in browser) or global (in Node.js)
JavaScript provides methods to explicitly set the value of this:
const person = { name: 'Alice', greet: function() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice"
function greet() { console.log(`Hello, I'm ${this.name}`); } const person = { name: 'Bob' }; greet.call(person); // "Hello, I'm Bob"
const person = { name: 'Charlie', greet: () => { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm undefined" (or global name if defined)
Use Cases:
ES6 introduced classes, which provide a clearer syntax for constructor functions and methods. Within class methods, this refers to the instance.
Exmaple:
const person = { name: 'Dana', greet: function() { const inner = () => { console.log(`Hello, I'm ${this.name}`); }; inner(); } }; person.greet(); // "Hello, I'm Dana"
Arrow Functions in Classes:
Arrow functions can be used for methods to inherit this from the class context, useful for callbacks.
const calculator = { value: 0, add: function(num) { this.value += num; return this.value; } }; console.log(calculator.add(5)); // 5 console.log(calculator.add(10)); // 15 const addFunction = calculator.add; console.log(addFunction(5)); // NaN (in non-strict mode, this.value is undefined + 5)
When passing methods as callbacks, the original context may be lost.
Problem
function Person(name) { this.name = name; } const alice = new Person('Alice'); console.log(alice.name); // "Alice"
Solution
Use bind to preserve context.
<button> <p><strong>Arrow Function Caveat:</strong><br> Using arrow functions in event handlers can lead to this referring to the surrounding scope instead of the event target.<br> <strong>Example:</strong><br> </p> <pre class="brush:php;toolbar:false">button.addEventListener('click', () => { console.log(this); // Global object or enclosing scope });
Arrow functions don’t have their own this, which can lead to unexpected behavior when used as methods.
Problem
function greet(greeting) { console.log(`${greeting}, I'm ${this.name}`); } const person = { name: 'Eve' }; greet.call(person, 'Hello'); // "Hello, I'm Eve"
Solution
Use regular functions for object methods.
greet.apply(person, ['Hi']); // "Hi, I'm Eve"
Unintentionally setting properties on the global object can lead to bugs.
Problem
const boundGreet = greet.bind(person); boundGreet('Hey'); // "Hey, I'm Eve"
Solution
Use strict mode or proper binding.
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } const dog = new Animal('Dog'); dog.speak(); // "Dog makes a noise."
In nested functions, this may not refer to the outer this. Solutions include using arrow functions or storing this in a variable.
Example with Arrow Function:
class Person { constructor(name) { this.name = name; } greet = () => { console.log(`Hello, I'm ${this.name}`); } } const john = new Person('John'); john.greet(); // "Hello, I'm John"
Example with Variable:
const obj = { name: 'Object', getName: function() { return this.name; } }; const getName = obj.getName; console.log(getName()); // undefined or global name
When using prototypes, this refers to the instance.
console.log(this === window); // true (in browser) console.log(this === global); // true (in Node.js)
The this keyword in JavaScript is a versatile and powerful feature that, when understood correctly, can greatly enhance your coding capabilities.
To truly cement your understanding of this, tackle the following challenging problems. Each problem is designed to test different aspects and edge cases of the this keyword in JavaScript. Solutions in the end.
function showThis() { console.log(this); } showThis(); // Window object (in browser) or global (in Node.js)
const person = { name: 'Alice', greet: function() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice"
function greet() { console.log(`Hello, I'm ${this.name}`); } const person = { name: 'Bob' }; greet.call(person); // "Hello, I'm Bob"
const person = { name: 'Charlie', greet: () => { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm undefined" (or global name if defined)
const person = { name: 'Dana', greet: function() { const inner = () => { console.log(`Hello, I'm ${this.name}`); }; inner(); } }; person.greet(); // "Hello, I'm Dana"
const calculator = { value: 0, add: function(num) { this.value += num; return this.value; } }; console.log(calculator.add(5)); // 5 console.log(calculator.add(10)); // 15 const addFunction = calculator.add; console.log(addFunction(5)); // NaN (in non-strict mode, this.value is undefined + 5)
function Person(name) { this.name = name; } const alice = new Person('Alice'); console.log(alice.name); // "Alice"
<button> <p><strong>Arrow Function Caveat:</strong><br> Using arrow functions in event handlers can lead to this referring to the surrounding scope instead of the event target.<br> <strong>Example:</strong><br> </p> <pre class="brush:php;toolbar:false">button.addEventListener('click', () => { console.log(this); // Global object or enclosing scope });
function greet(greeting) { console.log(`${greeting}, I'm ${this.name}`); } const person = { name: 'Eve' }; greet.call(person, 'Hello'); // "Hello, I'm Eve"
When getName is assigned to a variable and called without any object context, this defaults to the global object. In non-strict mode, this.name refers to the global name, which is 'Global'. In strict mode, this would be undefined, leading to an error.
greet.apply(person, ['Hi']); // "Hi, I'm Eve"
Arrow functions do not have their own this; they inherit it from the surrounding scope. In this case, the surrounding scope is the global context, where this.name is 'Global'.
const boundGreet = greet.bind(person); boundGreet('Hey'); // "Hey, I'm Eve"
Inside the setInterval callback, this refers to the global object (or is undefined in strict mode). Thus, this.seconds either increments window.seconds or throws an error in strict mode. The timer.seconds remains 0.
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } const dog = new Animal('Dog'); dog.speak(); // "Dog makes a noise."
After binding retrieveX to module, calling boundGetX() correctly sets this to module.
class Person { constructor(name) { this.name = name; } greet = () => { console.log(`Hello, I'm ${this.name}`); } } const john = new Person('John'); john.greet(); // "Hello, I'm John"
The arrow function getModel inherits this from the constructor, which refers to the newly created car instance.
const obj = { name: 'Object', getName: function() { return this.name; } }; const getName = obj.getName; console.log(getName()); // undefined or global name
In event handlers using regular functions, this refers to the DOM element that received the event, which is the button. Since the button doesn’t have a name property, this.name is undefined.
console.log(this === window); // true (in browser) console.log(this === global); // true (in Node.js)
function showThis() { console.log(this); } showThis(); // Window object (in browser) or global (in Node.js)
Inside the Promise constructor, this refers to the global object (or is undefined in strict mode). Thus, this.value is undefined (or causes an error in strict mode).
const person = { name: 'Alice', greet: function() { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm Alice"
The multiply function is bound with the first argument a as 2. When double(5) is called, it effectively computes multiply(2, 5).
function greet() { console.log(`Hello, I'm ${this.name}`); } const person = { name: 'Bob' }; greet.call(person); // "Hello, I'm Bob"
In the Dog class’s speak method, the setTimeout callback is a regular function. Thus, this inside the callback refers to the global object, not the dog instance. this.name is 'undefined' or causes an error if name is not defined globally.
const person = { name: 'Charlie', greet: () => { console.log(`Hello, I'm ${this.name}`); } }; person.greet(); // "Hello, I'm undefined" (or global name if defined)
To fix this, use an arrow function:
const person = { name: 'Dana', greet: function() { const inner = () => { console.log(`Hello, I'm ${this.name}`); }; inner(); } }; person.greet(); // "Hello, I'm Dana"
Now, it correctly logs:
const calculator = { value: 0, add: function(num) { this.value += num; return this.value; } }; console.log(calculator.add(5)); // 5 console.log(calculator.add(10)); // 15 const addFunction = calculator.add; console.log(addFunction(5)); // NaN (in non-strict mode, this.value is undefined + 5)
The above is the detailed content of Mastering the this Keyword in JavaScript: Never to look back again. For more information, please follow other related articles on the PHP Chinese website!