牢牢记住this的五种情况,不怕this
2023-11-07 03:13:59
在 JavaScript 中,this 是指向当前对象的一个指针。当一个函数被调用时,this 会被自动地设置为指向调用该函数的对象。理解 this 的行为对于编写健壮和可维护的 JavaScript 代码非常重要。
在本文中,我们将讨论 this 的五种常见情况,以及在这些情况下 this 如何工作。
- 作为对象方法的函数
当一个函数作为对象的方法被调用时,this 会被自动地设置为指向该对象。例如,考虑以下代码:
const person = {
name: 'John Doe',
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // 输出: "Hello, my name is John Doe."
在这个例子中,greet 函数作为 person 对象的方法被调用。因此,this 被自动地设置为指向 person 对象,并且 name 属性可以通过 this.name 访问。
- 作为构造函数的函数
当一个函数作为构造函数被调用时,this 会被自动地设置为指向一个新创建的对象。例如,考虑以下代码:
function Person(name) {
this.name = name;
}
const person = new Person('John Doe');
console.log(person.name); // 输出: "John Doe"
在这个例子中,Person 函数作为构造函数被调用。因此,this 被自动地设置为指向一个新创建的 Person 对象,并且 name 属性可以通过 this.name 访问。
- 作为独立函数的函数
当一个函数作为独立函数被调用时,this 会被自动地设置为指向全局对象。例如,考虑以下代码:
function greet() {
console.log(`Hello, my name is ${this.name}.`);
}
greet(); // 输出: "Hello, my name is undefined."
在这个例子中,greet 函数作为独立函数被调用。因此,this 被自动地设置为指向全局对象,并且 name 属性无法被访问,因为全局对象没有 name 属性。
- 作为事件处理程序的函数
当一个函数作为事件处理程序被调用时,this 会被自动地设置为指向 DOM 元素。例如,考虑以下代码:
<button onclick="greet()">Click me</button>
<script>
function greet() {
console.log(`Hello, my name is ${this.innerHTML}.`);
}
</script>
在这个例子中,greet 函数作为 button 元素的 onclick 事件处理程序被调用。因此,this 被自动地设置为指向 button 元素,并且 innerHTML 属性可以通过 this.innerHTML 访问。
- 作为箭头函数的函数
当一个函数作为箭头函数被调用时,this 会继承外层函数的 this 值。例如,考虑以下代码:
const person = {
name: 'John Doe',
greet: () => {
console.log(`Hello, my name is ${this.name}.`);
}
};
person.greet(); // 输出: "Hello, my name is undefined."
在这个例子中,greet 函数作为箭头函数被调用。因此,this 继承了 person 对象的 this 值,并且 name 属性可以通过 this.name 访问。
希望本文对您理解 this 的行为有所帮助。如果您有任何问题,请随时留言。