Home > Web Front-end > JS Tutorial > body text

There are several situations where this in js points to

下次还敢
Release: 2024-05-06 14:03:15
Original
301 people have browsed it

In JavaScript, the pointing types of this are: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.

There are several situations where this in js points to

The pointer of this in JavaScript

The type pointed by this

JavaScript, this points to the following types:

1. Global object

  • When a function is called in the global scope, this points to window object (in browsers) or global object (in Node.js).

2. Function call

  • When a function is called as a method, this points to the object containing the method.
  • For example: const person = { name: "John", greet: function() { console.log(this.name); }}; person.greet();

3. Constructor call

  • When calling a function using the new keyword, this points to the newly created object.
  • For example: const person = new Person("John");

##4. Event handler

    When an event handler (such as onclick) is called, this points to the element that triggered the event.
  • For example:

5. Arrow function

    The arrow function does not have its own this, it will inherit this from the outer scope.
  • For example:
  • const person = { name: "John", greet: () => console.log(this.name); };

Notes

    You can use the bind(), call() and apply() methods to explicitly set the point of this.
  • Arrow functions and class methods always bind this to the scope in which they are defined.

The above is the detailed content of There are several situations where this in js points to. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template