定义
this是js的一个关键字,this指向当前执行上下文中的对象。在不同的上下文中,this的值会有所不同。
不同上下文的this指向
全局上下文
在全局执行上下文中,this 指向全局对象。在浏览器中,这个全局对象是 window
,在Node.js中则是 global
。
console.log(this); // 在浏览器中输出 Window 对象
函数上下文
在普通函数内,this 默认为全局对象(在严格模式下为 undefined
)。但是如果通过对象调用一个方法,this 会指向那个对象。
function showThis() {
console.log(this);
}
showThis();// 在浏览器中输出Window对象或undefined
const obj = {
name: 'Tom',
fn1: function () {
console.log(this.name);
}
};
obj.fn1(); // 输出'Tom'
构造函数上下文
当使用 new
关键字调用构造函数时,this 指向新创建的实例对象。
function Person(name) {
this.name = name;
}
const p = new Person('Alice');
console.log(p.name); // 输出'Alice'
箭头函数的上下文
箭头函数不会创建自己的 this
值,它会从外部上下文中继承 this
。
const obj = {
value: 42,
getValue: function() {
return () => this.value; // 这里的 this 继承自 getValue 的上下文
}
};
const func = obj.getValue();
console.log(func()); // 输出 42
function foo() {
this.value = '111';
(() =>