Home  >  Article  >  Web Front-end  >  The meaning of this in js

The meaning of this in js

下次还敢
下次还敢Original
2024-05-01 09:36:16439browse

In JavaScript, the this keyword points to the object in the current execution context. Specifically: the global execution context points to the window object, the function execution context points to the object to which the function belongs, the method execution context points to the object of the calling method, the function inherits the this object of the parent function

The meaning of this in js

The meaning of this in JavaScript

In JavaScript, this is a special keyword that points to the object in the current execution context. This may sound a bit complicated, but it's actually easy to understand.

Execution context

JavaScript code runs in different contexts when executed, called execution context. Each execution context has its own this object.

Global execution context

When JavaScript code is run in the browser, it first runs in the global execution context. In this case, this points to the window object.

Function Execution Context

When a function is called, it creates its own execution context. In this context, this points to the object the function belongs to.

Method execution context

When an object's method is called, it creates its own execution context. In this case, this points to the object on which the method is called.

Arrow functions

Arrow functions are an exception. They do not create their own execution context, but inherit the execution context of the parent function. Therefore, this in an arrow function always points to the this object of the parent function.

Practical Example

The following example shows how this can reference different objects based on different execution contexts:

<code class="javascript">// 全局执行上下文
console.log(this); // 输出: Window

// 函数执行上下文
function myFunction() {
  console.log(this); // 输出: Window
}
myFunction();

// 方法执行上下文
const obj = {
  name: 'John',
  sayHello: function() {
    console.log(this.name); // 输出: John
  }
};
obj.sayHello();

// 箭头函数
const arrowFunction = () => {
  console.log(this); // 输出: Window
};
arrowFunction();</code>

By understanding this how objects work in JavaScript, you can write cleaner, more maintainable code.

The above is the detailed content of The meaning of this in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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