理解JavaScript中的this
一、this出现的几种情况
1、构造函数中的this
1 2 3 4 | function Fn(){ console.log( this ); } var obj1 = new Fn(); //obj1, 函数Fn中的this指向实例对象obj1 |
2、普通函数中的this
1 2 3 4 5 | function Fn1(){ console.log( this ); } Fn1(); //window, Fn1属于window全局对象的一个属性,即:Fn1()===window.Fn1(),函数Fn1中的this指向window对象 Fn()===window.Fn(); //window, Fn属于window全局对象的一个属性,即:Fn()===window.Fn(),函数Fn中的this指向window对象 |
3、对象中的this
1 2 3 4 5 6 7 8 | var obj = { that: this , fn: function (){ console.log( this ); } } console.log(obj.that); //window, this不存在Object对象中的,this指向window全局对象 obj.fn(); //obj, this指向调用其所在函数的对象 |
二、总结:
1、this不存在Object对象中的,它只存在一个Function类型的函数中
2、this指向使用new操作符实例化其所在函数的实例对象
3、this还指向调用其所在函数的对象
三、误区:
1、注意在全局函数中的this
1 2 3 4 5 6 7 8 9 | var obj = { fn: function (){ function test(){ console.log( this ); } test(); } } obj.fn(); //window, test属于window对象的属性,因此this指向的是window对象,而不是obj对象 |
2、上面的例子中,this一般被误认为obj对象,其实不是的,它指向window全局对象,但可以通过obj中的一个局部变量来指向obj
1 2 3 4 5 6 7 8 9 10 | var obj = { fn: function (){ var self = this ; function test(){ console.log(self); //用self来指向obj对象 } test(); } } obj.fn(); //obj |
3、方法的赋值表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var obj = { prototype: "value" , fn: function (){ var self = this ; function test(){ console.log( this .prototype); //undefined,this指向window对象 console.log(self.prototype); //value,用self来指向obj对象 } test(); } } obj.fn(); var fn = obj.fn; fn(); //输出两个undefined,this指向window对象, 上一句中变量fn是window对象的一个属性,此时的self变量保存的还是window对象 |
综上:this总是指向其所在函数类型的对象以及调用其所在函数中的(顶层)对象.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构