JS 中 this 关键字的全面解析
this 是 JavaScript 中最具动态特性的关键字,其指向由函数调用方式决定。本文通过场景化示例解析 this 的常见行为规则。
一、全局作用域中的 this
非严格模式
console.log(this); // 浏览器输出: Window 对象;Node.js 输出: global 对象
严格模式
(function() {
'use strict';
console.log(this); // 输出: undefined
})();
二、函数调用场景
1. 普通函数调用
非严格模式
function showGlobalThis() {
console.log(this); // 输出全局对象(浏览器:Window,Node.js:global)
}
showGlobalThis();
严格模式
(function() {
'use strict';
function showUndefinedThis() {
console.log(this); // 输出: undefined
}
showUndefinedThis();
})();
2. 对象方法调用
const user = {
name: 'Jayce',
introduce: function() {
console.log(`User: ${this.name}`); // this → user 对象
}
};
user.introduce(); // 输出: "User: Jayce"
3. 构造函数调用
function User(name) {
this.name = name; // this → 新创建的实例
}
const user1 = new User('Jayce');
console.log(user1); // 输出: User { name: 'Jayce' }
三、箭头函数的 this
箭头函数继承定义时的外层上下文 this:
const timerExample = {
start: function() {
setTimeout(() => {
console.log(this); // 继承 start 方法的 this(即 timerExample 对象)
}, 1000);
}
};
timerExample.start();
四、显式绑定方法
1. call() - 立即调用
function showInfo(role) {
console.log(`${role}: ${this.name}`);
}
const person = { name: 'Jayce' };
showInfo.call(person, 'Developer'); // 输出: "Developer: Jayce"
2. apply() - 参数数组
showInfo.apply(person, ['Engineer']); // 输出: "Engineer: Jayce"
3. bind() - 永久绑定
const boundFunc = showInfo.bind(person);
boundFunc('Designer'); // 输出: "Designer: Jayce"
五、事件处理场景
<button id="demoBtn">Click Me</button>
<script>
document.getElementById('demoBtn').addEventListener('click', function() {
console.log(this); // 输出: <button id="demoBtn"> 元素对象
});
</script>
关键规则总结
| 调用场景 | this 指向 |
|---|---|
| 普通函数调用 | 严格模式:undefined,非严格模式:全局对象 |
| 对象方法调用 | 调用该方法的对象 |
| 构造函数调用 | 新创建的实例对象 |
| 箭头函数 | 定义时的外层上下文 this |
| 事件处理函数 | 触发事件的 DOM 元素 |
| 显式绑定(call/apply/bind) | 指定的绑定对象 |
理解要点:
this绑定在函数调用时,而非定义时- 箭头函数的
this具有词法作用域特性 - 严格模式会改变默认绑定行为
- 优先使用
bind避免意外绑定问题
通过掌握这些规则,可以更精准地控制 JavaScript 中的上下文指向,编写出更健壮的代码。

785

被折叠的 条评论
为什么被折叠?



