JS 中 this 关键字的全面解析

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)指定的绑定对象

理解要点

  1. this 绑定在函数调用时,而非定义时
  2. 箭头函数的 this 具有词法作用域特性
  3. 严格模式会改变默认绑定行为
  4. 优先使用 bind 避免意外绑定问题

通过掌握这些规则,可以更精准地控制 JavaScript 中的上下文指向,编写出更健壮的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值