Home Web Front-end JS Tutorial Mastering the &#this&# Keyword in JavaScript: Never to look back again

Mastering the &#this&# Keyword in JavaScript: Never to look back again

Jan 06, 2025 am 06:59 AM

Mastering the

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.

Introduction to this

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.

1. Global Context

When not inside any function, this refers to the global object.

  • In Browsers: The global object is window.
  • In Node.js: The global object is global.

Example

console.log(this === window); // true (in browser)
console.log(this === global); // true (in Node.js)
Copy after login
Copy after login
Copy after login
Copy after login

Note: In strict mode ('use strict';), this in the global context remains the global object.

2. Function Context

I. Regular Functions

In regular functions, this is determined by how the function is called.

  • Default Binding: If a function is called without any context, this refers to the global object (or undefined in strict mode).

Example:

function showThis() {
  console.log(this);
}

showThis(); // Window object (in browser) or global (in Node.js)
Copy after login
Copy after login
Copy after login
Copy after login
  • Implicit Binding: When a function is called as a method of an object, this refers to that object.

Example

const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

person.greet(); // "Hello, I'm Alice"
Copy after login
Copy after login
Copy after login
Copy after login

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"
Copy after login
Copy after login
Copy after login
Copy after login

II. Arrow Functions

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)
Copy after login
Copy after login
Copy after login
Copy after login

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"
Copy after login
Copy after login
Copy after login
Copy after login

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)
Copy after login
Copy after login
Copy after login
Copy after login

3. Constructor Functions and this

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)
Copy after login
Copy after login
Copy after login
Copy after login

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.

4. The this in Event Handlers

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)
Copy after login
Copy after login
Copy after login
Copy after login

5. Explicit Binding with call, apply, and bind

JavaScript provides methods to explicitly set the value of this:

  • call: Invokes the function with this set to the first argument, followed by function arguments.
const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

person.greet(); // "Hello, I'm Alice"
Copy after login
Copy after login
Copy after login
Copy after login
  • apply: Similar to call, but accepts arguments as an array.
function greet() {
  console.log(`Hello, I'm ${this.name}`);
}

const person = { name: 'Bob' };
greet.call(person); // "Hello, I'm Bob"
Copy after login
Copy after login
Copy after login
Copy after login
  • bind: Returns a new function with this bound to the first argument.
const person = {
  name: 'Charlie',
  greet: () => {
    console.log(`Hello, I'm ${this.name}`);
  }
};

person.greet(); // "Hello, I'm undefined" (or global name if defined)
Copy after login
Copy after login
Copy after login
Copy after login

Use Cases:

  • Borrowing methods from other objects.
  • Ensuring this remains consistent in callbacks.

6. this in Classes

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"
Copy after login
Copy after login
Copy after login
Copy after login

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)
Copy after login
Copy after login
Copy after login
Copy after login

Common Pitfalls and Best Practices

I. Losing this Context

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"
Copy after login
Copy after login

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
});
Copy after login
Copy after login

II. Using Arrow Functions Improperly

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"
Copy after login
Copy after login

Solution
Use regular functions for object methods.

greet.apply(person, ['Hi']); // "Hi, I'm Eve"
Copy after login
Copy after login

III. Avoiding Global this

Unintentionally setting properties on the global object can lead to bugs.

Problem

const boundGreet = greet.bind(person);
boundGreet('Hey'); // "Hey, I'm Eve"
Copy after login
Copy after login

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."
Copy after login
Copy after login

Advanced Concepts

I. this in Nested Functions

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"
Copy after login
Copy after login

Example with Variable:

const obj = {
  name: 'Object',
  getName: function() {
    return this.name;
  }
};

const getName = obj.getName;
console.log(getName()); // undefined or global name
Copy after login
Copy after login

II. this with Prototypes

When using prototypes, this refers to the instance.

console.log(this === window); // true (in browser)
console.log(this === global); // true (in Node.js)
Copy after login
Copy after login
Copy after login
Copy after login

Conclusion

The this keyword in JavaScript is a versatile and powerful feature that, when understood correctly, can greatly enhance your coding capabilities.


10 Tricky Problems to Master this

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.

Problem 1: The Mysterious Output

function showThis() {
  console.log(this);
}

showThis(); // Window object (in browser) or global (in Node.js)
Copy after login
Copy after login
Copy after login
Copy after login

Problem 2: Arrow Function Surprise

const person = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, I'm ${this.name}`);
  }
};

person.greet(); // "Hello, I'm Alice"
Copy after login
Copy after login
Copy after login
Copy after login

Problem 3: Binding this in a Callback

function greet() {
  console.log(`Hello, I'm ${this.name}`);
}

const person = { name: 'Bob' };
greet.call(person); // "Hello, I'm Bob"
Copy after login
Copy after login
Copy after login
Copy after login

Problem 4: Using bind Correctly

const person = {
  name: 'Charlie',
  greet: () => {
    console.log(`Hello, I'm ${this.name}`);
  }
};

person.greet(); // "Hello, I'm undefined" (or global name if defined)
Copy after login
Copy after login
Copy after login
Copy after login

Problem 5: this in Constructor Functions

const person = {
  name: 'Dana',
  greet: function() {
    const inner = () => {
      console.log(`Hello, I'm ${this.name}`);
    };
    inner();
  }
};

person.greet(); // "Hello, I'm Dana"
Copy after login
Copy after login
Copy after login
Copy after login

Problem 6: Event Handler Context

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)
Copy after login
Copy after login
Copy after login
Copy after login

Problem 8: this in Promises

function Person(name) {
  this.name = name;
}

const alice = new Person('Alice');
console.log(alice.name); // "Alice"
Copy after login
Copy after login

Problem 9: Chaining with bind

<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
});
Copy after login
Copy after login

Problem 10: this with Classes and Inheritance

function greet(greeting) {
  console.log(`${greeting}, I'm ${this.name}`);
}

const person = { name: 'Eve' };
greet.call(person, 'Hello'); // "Hello, I'm Eve"
Copy after login
Copy after login

Solutions to Tricky Problems

Solution to Problem 1:

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"
Copy after login
Copy after login

Solution to Problem 2:

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"
Copy after login
Copy after login

Solution to Problem 3:

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."
Copy after login
Copy after login

Solution to Problem 4:

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"
Copy after login
Copy after login

Solution to Problem 5:

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
Copy after login
Copy after login

Solution to Problem 6:

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)
Copy after login
Copy after login
Copy after login
Copy after login

Solution to Problem 7:

  • First console.log(this.name); inside outerFunc refers to obj, so it prints 'Outer'.
  • Second console.log(this.name); inside innerFunc refers to the global object, so it prints 'Global' or undefined in strict mode.
function showThis() {
  console.log(this);
}

showThis(); // Window object (in browser) or global (in Node.js)
Copy after login
Copy after login
Copy after login
Copy after login

Solution to Problem 8:

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"
Copy after login
Copy after login
Copy after login
Copy after login

Solution to Problem 9:

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"
Copy after login
Copy after login
Copy after login
Copy after login

Solution to Problem 10:

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)
Copy after login
Copy after login
Copy after login
Copy after login

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"
Copy after login
Copy after login
Copy after login
Copy after login

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)
Copy after login
Copy after login
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles