This in JavaScript is a vexing topic. Where it points depends on how the function is called, which makes understanding it complex and difficult. This article will take you deep into the issue of this pointing in JavaScript and provide some code examples to help you understand better.
Beginning
In JavaScript, this is a special keyword that refers to the object currently executing code. However, the pointer of this is not fixed, but changes dynamically according to how the function is called. This flexibility creates a lot of confusion for developers, especially when it comes to nested functions, object methods, and constructors.
Understand the direction of this
this in global context
In the global context, this points to the global object (window object in browsers). This means that using this in the global scope will point to the window object.
console.log(this === window); // true
this in object methods
When a function is called as a method on an object, this points to the object on which the method was called.
const obj = {
name: 'Alice',
greet: function() {
console.log('Hello, ' + this.name);
}
};
obj.greet(); // 输出:Hello, Alice
this in the constructor
In the constructor, this points to the instance to be created.
function Person(name) {
this.name = name;
}
const person1 = new Person('Bob');
console.log(person1.name); // 输出:Bob
this in arrow function
The this point of the arrow function is the same as the outer context when it is defined, rather than changing dynamically.
const obj = {
name: 'Alice',
greet: function() {
const innerFunc = () => {
console.log('Hello, ' + this.name);
};
innerFunc();
}
};
obj.greet(); // 输出:Hello, Alice
Summarize
This article introduces the problem of this pointing in JavaScript and provides some code examples to help readers better understand. To understand this in depth, the key is to be familiar with the pointing rules of this in different situations, and practice and think more in actual development. I hope this article can help you better master the usage skills of this in JavaScript and avoid confusion and errors during the development process.