this 指向
this 的指向在 JavaScript 中是动态的,取决于函数的调用方式。理解这些规则对于正确使用 this 关键字和避免常见的陷阱非常重要。
以下是 this 指向的几种常见规则:
1. 全局上下文(默认绑定)
在全局上下文中或在简单函数调用中,this 指向全局对象(在浏览器中是 window,在 Node.js 中是 global)。
javascript
console.log(this); // 在浏览器中输出 window 对象
console.log(this); // 在浏览器中输出 window 对象
2. 函数调用
在普通函数调用中,this 默认指向全局对象(在严格模式下,this 是 undefined)。
javascript
function foo() {
console.log(this);
}
foo(); // 在非严格模式下输出 window,在严格模式下输出 undefined
function foo() {
console.log(this);
}
foo(); // 在非严格模式下输出 window,在严格模式下输出 undefined
3. 对象方法(隐式绑定)
当函数作为对象的方法调用时,this 指向调用该方法的对象。
javascript
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
obj.greet(); // 输出 'Alice'
const obj = {
name: 'Alice',
greet: function() {
console.log(this.name);
}
};
obj.greet(); // 输出 'Alice'
4. 显式绑定
使用 call、apply 或 bind,可以显式地设置 this 的值。
javascript
function greet() {
console.log(this.name);
}
const obj = { name: 'Charlie' };
greet.call(obj); // 输出 'Charlie'
greet.apply(obj); // 输出 'Charlie'
function greet() {
console.log(this.name);
}
const obj = { name: 'Charlie' };
greet.call(obj); // 输出 'Charlie'
greet.apply(obj); // 输出 'Charlie'
5. 构造函数(new 绑定)
当函数作为构造函数使用(使用 new 关键字),this 指向新创建的实例。
javascript
function Person(name) {
this.name = name;
}
const person = new Person('Bob');
console.log(person.name); // 输出 'Bob'
function Person(name) {
this.name = name;
}
const person = new Person('Bob');
console.log(person.name); // 输出 'Bob'
6. 箭头函数
箭头函数没有自己的 this,它会捕获其所在上下文的 this 值(即词法作用域中的 this)。
javascript
const obj = {
name: 'Eve',
greet: function() {
const innerFunction = () => {
console.log(this.name);
};
innerFunction();
}
};
obj.greet(); // 输出 'Eve'
const obj = {
name: 'Eve',
greet: function() {
const innerFunction = () => {
console.log(this.name);
};
innerFunction();
}
};
obj.greet(); // 输出 'Eve'
7. DOM 事件处理程序
在事件处理程序中,this 指向触发事件的 DOM 元素。
javascript
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this); // 输出被点击的按钮元素
});
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this); // 输出被点击的按钮元素
});
8. setTimeout
中的 this
指向 window。
javascript
const obj = {
name: 'Hank',
greet: function() {
setTimeout(function() {
console.log(this.name);
}, 1000);
}
};
obj.greet(); // window
const obj = {
name: 'Hank',
greet: function() {
setTimeout(function() {
console.log(this.name);
}, 1000);
}
};
obj.greet(); // window