当前位置: 首页 > news >正文

JavaScript 中 this 指向详解

JavaScript 中 this 指向详解(含多种绑定形式与陷阱)

this 是 JavaScript 中用于函数执行上下文的特殊关键字,表示函数运行时的所属对象。它的指向取决于函数的调用方式


🧠 为什么存在 this

  • 提供统一的上下文访问机制。
  • 支持对象方法复用
  • 便于类/构造函数共享行为。

🧩 一、四种 this 绑定规则详解

1️⃣ 默认绑定(Direct Function Call)

function sayHi() {console.log(this);
}
sayHi(); // 非严格模式:window;严格模式:undefined
  • 非严格模式this 指向全局对象 window
  • 严格模式thisundefined

2️⃣ 隐式绑定(Object Method Call)

const person = {name: 'Tom',greet() {console.log(this.name);}
};
person.greet(); // 输出 Tom
  • 函数通过对象调用时,this 指向该对象。
⚠️ 隐式绑定丢失示例:
const greetFn = person.greet;
greetFn(); // undefined 或 window 上的 name
  • 函数独立引用后,脱离了原对象,变为默认绑定。

3️⃣ 显式绑定(callapplybind

function introduce(lang) {console.log(`${lang}: I'm ${this.name}`);
}
const user = { name: 'Alice' };introduce.call(user, 'EN');
introduce.apply(user, ['FR']);
const boundFn = introduce.bind(user, 'CN');
boundFn();
方法是否立即执行参数传递方式
call逗号分隔参数
apply数组形式参数
bind返回绑定后的新函数

4️⃣ new 绑定(构造函数)

function Person(name) {this.name = name;
}
const p = new Person('Eve');
console.log(p.name); // Eve

等价执行流程:

function Person(name) {// this = {}this.name = name;// return this;
}

🔢 二、this 绑定优先级(从高到低)

new 绑定 > 显式绑定(bind/call/apply)> 隐式绑定 > 默认绑定
function showName() {console.log(this.name);
}
const obj = { name: 'Leo' };
const bound = showName.bind(obj);
const n = new bound(); // this 指向新创建的对象,而非 obj

🚀 三、箭头函数中的 this

const obj = {name: 'Arrow',say() {const arrowFn = () => {console.log(this.name);};arrowFn();}
};
obj.say(); // 输出:Arrow

箭头函数不会创建自己的 this

const person = {name: 'Mike',greet: () => {console.log(this.name);}
};
person.greet(); // undefined
  • this 取决于定义时的上下文,不是调用者。

🔍 四、this 在不同场景下的指向

✅ 事件监听器中

document.querySelector('#btn').addEventListener('click', function () {console.log(this); // 触发事件的元素
});
document.querySelector('#btn').addEventListener('click', () => {console.log(this); // 外层作用域(通常为 window)
});

✅ setTimeout/setInterval

setTimeout(function () {console.log(this); // window
}, 1000);

✅ class 方法

class Person {constructor(name) {this.name = name;this.sayHi = this.sayHi.bind(this);}sayHi() {console.log(this.name);}
}

或使用箭头函数:

class Person {name = 'Anna';sayHi = () => {console.log(this.name);}
}

⚠️ 五、常见陷阱与解决方案

this 丢失:异步/回调场景

const obj = {name: 'Obj',run() {setTimeout(this.say, 1000); // ❌ 默认绑定},say() {console.log(this.name);}
};
obj.run(); // undefined

✅ 解决方案:

setTimeout(this.say.bind(this), 1000);
// 或
setTimeout(() => this.say(), 1000);

✅ this 绑定规则总结表

调用方式this 指向
普通函数全局对象(非严格);undefined(严格)
对象方法该对象
箭头函数定义时的外层作用域
构造函数(new)新创建的实例对象
call/apply/bind显式传入的对象
事件监听器(function)触发事件的 DOM 元素
事件监听器(箭头)外层作用域
setTimeout/setInterval全局对象
class 方法调用者(需手动绑定)

📚 建议与技巧

  • 在回调中优先使用箭头函数,避免 this 丢失。
  • 使用 .bind(this) 或箭头函数保证类方法中 this 正确。
  • 避免函数“脱离对象”后独立调用。
  • 善用箭头函数与显式绑定,减少 this 混乱。


文章转载自:
http://burny.wanhuigw.com
http://annulation.wanhuigw.com
http://benedict.wanhuigw.com
http://amfortas.wanhuigw.com
http://adamsite.wanhuigw.com
http://barnstormer.wanhuigw.com
http://chaudfroid.wanhuigw.com
http://antimycotic.wanhuigw.com
http://airdent.wanhuigw.com
http://camberwell.wanhuigw.com
http://astrophysicist.wanhuigw.com
http://advisory.wanhuigw.com
http://cheetah.wanhuigw.com
http://cheroot.wanhuigw.com
http://allot.wanhuigw.com
http://apomixis.wanhuigw.com
http://aerostat.wanhuigw.com
http://brassware.wanhuigw.com
http://astound.wanhuigw.com
http://binge.wanhuigw.com
http://anglesmith.wanhuigw.com
http://batter.wanhuigw.com
http://bandage.wanhuigw.com
http://carbohydrase.wanhuigw.com
http://bezant.wanhuigw.com
http://antimorph.wanhuigw.com
http://antares.wanhuigw.com
http://acciaccatura.wanhuigw.com
http://bogota.wanhuigw.com
http://btu.wanhuigw.com
http://www.dtcms.com/a/215830.html

相关文章:

  • 力扣四道题,力扣LCR 016无重复字符的最长子串力扣452.用最小数量的箭引爆气球LCR026.重排链表力扣.1765地图中的最高点
  • 分布式项目保证消息幂等性的常见策略
  • 视频监控汇聚平台EasyCVR工业与安全监控:防爆摄像机的安全应用与注意事项
  • 嵌入式Linux快速入门第1~2章
  • redis五种数据结构底层实现
  • React--》掌握react组件库设计与架构规划
  • 卷积神经网络(CNN)入门学习笔记
  • 递归函数,数学表达式转化成递归函数
  • JavaSE核心知识点04工具04-03(Maven)
  • Electron 桌面程序读取dll动态库
  • 【React】-组件中实现高性能鼠标跟随提示框的完整优化过程
  • 模板应用更新同步到所有开发中的应用
  • 图片压缩工具 | Electron+Vue3+Rsbuild开发桌面应用
  • React useEffect和useEffectLa
  • 鸿蒙OSUniApp 实现带搜索功能的下拉菜单#三方框架 #Uniapp
  • element的el-table翻页选中功能
  • Kubernetes Admission Controller (准入控制器)详解:作用、原理、常见类型
  • DRF的使用
  • 计算机系统结构-第四章节-背诵
  • openpi π₀ 项目部署运行逻辑(四)——机器人主控程序 main.py — aloha_real
  • 使用Gemini, LangChain, Gradio打造一个书籍推荐系统 (第三部分)
  • MySQL问题:主要索引类型(聚簇、辅助、覆盖、前缀)
  • Debian 11 之使用hostapd与dnsmasq进行AP设置
  • C++ STL 容器:List 深度解析与实践指南
  • 手机收不到WiFi,手动输入WiFi名称进行连接不不行,可能是WiFi频道设置不对
  • 仿真环境中机器人抓取与操作上手指南
  • 从零实现本地语音识别(FunASR)
  • Vue3 封装el-table组件
  • 13. CSS定位与伪类/伪元素
  • 从 PyTorch 到 TensorFlow Lite:模型训练与推理