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

The role of this in js

下次还敢
Release: 2024-05-06 13:45:24
Original
696 people have browsed it

In JavaScript, this is a special keyword that points to the context object of the currently executing code: Function context: this points to the global object window. Method context: this points to the object on which the method is called. Constructor context: this points to the new object being created. Event listener context: this points to the element that triggered the event. Arrow function context: this inherits this from the parent scope.

The role of this in js

this in JavaScript

In JavaScript, this is a special keyword that points to the context object of the currently executing code. Its value varies depending on the context because it can refer to a function, method, or object.

Function context

In a function context, this always points to the global object, that is, the window object. Therefore, when accessing this within a function, global variables and functions can be accessed.

<code class="js">function sayHello() {
  console.log(this); // 输出: Window {...}
}</code>
Copy after login

Method context

In a method context, this always points to the object on which the method is called. This allows methods to access the object's properties and methods.

<code class="js">const person = {
  name: "John",
  sayName: function () {
    console.log(this.name); // 输出: John
  },
};</code>
Copy after login

Constructor context

The constructor is a function used to create and initialize objects. In constructor context, this points to the new object being created.

<code class="js">function Person(name) {
  this.name = name;
}

const person1 = new Person("John");
console.log(person1.name); // 输出: John</code>
Copy after login

Other contexts

In addition to these primary contexts, this can also be used as:

  • Event listener context: In an event listener, this points to the element that triggered the event.
  • Arrow function context: this in an arrow function inherits this in its parent scope.

Notes

  • In strict mode, in the function context, this does not point to the global object. If you want to access global objects, you need to use the window object.
  • The bind(), call() and apply() methods were introduced in ES6 for explicitly setting or changing ## The value of #this.

The above is the detailed content of The role of this in js. 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