JavaScript this 关键字
最后修改于 2025 年 4 月 16 日
在本文中,我们将探讨 JavaScript this 关键字,它指的是执行代码的上下文。理解 this 对于 JavaScript 中的面向对象编程至关重要。
this 关键字
JavaScript 中的 this 关键字指的是它所属的对象。它的值由函数的调用方式决定(运行时绑定)。在大多数情况下,this 指的是拥有当前正在执行代码的对象。
this 的值会根据执行上下文而改变。在全局范围内,this 指的是全局对象(在浏览器中是 window)。在方法内部,this 指的是拥有者对象。
箭头函数没有自己的 this 绑定。相反,它们在创建时从父作用域继承 this。这使得箭头函数在回调函数和事件处理程序中特别有用。
全局上下文
在全局执行上下文中,this 指的是全局对象。
console.log(this === window); // true in browser this.globalVar = 'Hello'; console.log(window.globalVar); // 'Hello'
在浏览器环境中,全局对象是 window。当我们在全局范围内为 this 分配一个属性时,它就变成了一个全局变量。这说明了 this 指的是全局对象。
$ node main.js true Hello
函数上下文
在常规函数中,this 取决于函数的调用方式。
function showThis() {
console.log(this);
}
showThis(); // window/global in non-strict, undefined in strict
在非严格模式下,函数中的 this 指的是全局对象。在严格模式下,它是 undefined。这个例子展示了函数调用中 this 的默认绑定。
$ node main.js
Object [global] {
// ... global object properties
}
方法上下文
当一个函数作为对象的方法被调用时,this 指的是该对象。
const person = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet();
在这里,greet 方法内部的 this 指的是 person 对象。我们可以通过 this 访问对象的属性。这被称为隐式绑定。
$ node main.js Hello, my name is John
构造函数上下文
在构造函数中,this 指的是新创建的实例。
function Car(make, model) {
this.make = make;
this.model = model;
this.info = function() {
console.log(`${this.make} ${this.model}`);
};
}
const myCar = new Car('Toyota', 'Camry');
myCar.info();
当使用 new 调用时,构造函数的 this 指向正在创建的新对象。new 关键字创建一个新对象并将 this 设置为引用它。
$ node main.js Toyota Camry
使用 call 和 apply 的显式绑定
我们可以使用 call 或 apply 显式地设置 this。
function introduce(lang1, lang2) {
console.log(`My name is ${this.name} and I know ${lang1} and ${lang2}`);
}
const person = { name: 'Alice' };
introduce.call(person, 'JavaScript', 'Python');
introduce.apply(person, ['Ruby', 'Java']);
call 和 apply 都使用特定的 this 值调用函数。 区别在于参数的传递方式。 这对于在对象之间借用方法很有用。
$ node main.js My name is Alice and I know JavaScript and Python My name is Alice and I know Ruby and Java
箭头函数和 this
箭头函数没有自己的 this,但从封闭的上下文中继承它。
const obj = {
name: 'Bob',
regularFunc: function() {
console.log(this.name);
},
arrowFunc: () => {
console.log(this.name);
}
};
obj.regularFunc(); // 'Bob'
obj.arrowFunc(); // undefined (or window.name in browser)
箭头函数的 this 来自其词法作用域(它定义的位置)。在这种情况下,它从全局作用域继承 this,而不是从 obj 继承。
$ node main.js Bob undefined
事件处理程序和 this
在 DOM 事件处理程序中,this 指的是接收事件的元素。
// Assuming this runs in browser with a button element
document.querySelector('button').addEventListener('click', function() {
console.log(this); // the button element
});
// With arrow function
document.querySelector('button').addEventListener('click', () => {
console.log(this); // window (lexical this)
});
事件处理程序中的常规函数将 this 设置为该元素。 箭头函数保持其词法 this 绑定。 在处理 DOM 事件时,这种差异很重要。
// Output depends on browser environment
来源
在本文中,我们探讨了 JavaScript this 关键字及其各种上下文。 理解 this 对于有效的 JavaScript 编程至关重要。