this指向 apply/call() 可以把 this 引用到任意对象
this关键词指的是它所属的对象 => [谁调用指向谁]
方法中, this 指的是所属者对象; example:
const person = {
firstName: "Bill",
lastName : "Gates",
id : 678,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
单独情况下 this 指向全局 window 对象 example:
- const x = this; // this是全局对象[Object window]
在函数中 this 也是全局 window 对象
- function a() {console.log(this)} => 输出[Object window]
- Remark JS严格模式下, 函数中的 this 为undefined
- function a() {
'use strict'; // 严格模式
console.log(this); // 输出undefined
}
在事件中, this 指的是接受事件的元素;
- example: button onclick="this.style.display = 'none'" 点击删除 /button
this 绑定方法: 对象绑定和显式 apply/call() 绑定;
对象绑定法
const person = {
age: 18,
sex: '男',
name: 'Boolean',
speak: function() {
return this;
},
};
显式绑定法 apply/call();
- apply/call()都是JS预定义的方法, 他们都可以用于将一个对象作为参数调用对象方法
- FOR example
const person1 = {
nameFunction: function() {
return this.name + this.sex + this.age + '岁';
},
};
const person2 = {
age: 20,
sex: '女',
name: 'Alone'
};
person1.nameFunction.call(person2);
箭头函数中的 this
与常规函数相比较箭头函数里面没有 this 的绑定
在常规函数中,关键字 this 表示调用该函数的对象,可以是窗口、文档、按钮或其他任何东西。
对于箭头函数中的 this 始终表示定义箭头函数的对象
总结:this 谁调用指向谁
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义