JavaScript严格模式下关于this的几种指向详解
前言
相信不少人在学习或者使用Javascript的时候,都曾经被 JavaScript 中的 this 弄晕了,那么本文就来整理总结一下在严格模式下 this 的几种指向。
一、全局作用域中的this
在严格模式下,在全局作用域中,this指向window对象。
1
2
3
4
5
6
7
8
|
"use strict" ; console.log( "严格模式" ); console.log( "在全局作用域中的this" ); console.log( "this.document === document" , this .document === document); console.log( "this === window" , this === window); this .a = 9804; console.log( 'this.a === window.a===' ,window.a); |
二、全局作用域中函数中的this
在严格模式下,这种函数中的this等于undefined。不是严格模式时,这里的this指向window。在react中render()里的this是指向组件的实例对象。注意区分是render()里的this还是函数中的this。(这两个this指向不同,所以没法在全局作用域的函数中直接调用this取值)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
"use strict" ; console.log( "严格模式" ); console.log( '在全局作用域中函数中的this' ); function f1(){ console.log( this ); } function f2(){ function f3(){ console.log( this ); } f3(); } f1(); f2(); |
三、 对象的函数(方法)中的this
在严格模式下,对象的函数中的this指向调用函数的对象实例
1
2
3
4
5
6
7
8
9
10
|
"use strict" ; console.log( "严格模式" ); console.log( "在对象的函数中的this" ); var o = new Object(); o.a = 'o.a' ; o.f5 = function (){ return this .a; } console.log(o.f5()); |
四、构造函数的this
在严格模式下,构造函数中的this指向构造函数创建的对象实例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
"use strict" ; console.log( "严格模式" ); console.log( "构造函数中的this" ); function constru(){ this .a = 'constru.a' ; this .f2 = function (){ console.log( this .b); return this .a; } } var o2 = new constru(); o2.b = 'o2.b' ; console.log(o2.f2()); |
五、事件处理函数中的this
在严格模式下,在事件处理函数中,this指向触发事件的目标对象。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
"use strict" ; function blue_it(e){ if ( this === e.target){ this .style.backgroundColor = "#00f" ; } } var elements = document.getElementsByTagName( '*' ); for ( var i=0 ; i<elements.length ; i++){ elements[i].onclick = blue_it; } //这段代码的作用是使被单击的元素背景色变为蓝色 |
六、内联事件处理函数中的this
在严格模式下,在内联事件处理函数中,有以下两种情况:
1
2
3
4
5
6
7
8
9
|
< button onclick = "alert((function(){'use strict'; return this})());" > 内联事件处理1 </ button > <!-- 警告窗口中的字符为undefined --> < button onclick = "'use strict'; alert(this.tagName.toLowerCase());" > 内联事件处理2 </ button > <!-- 警告窗口中的字符为button --> |
注意:严格模式全局作用域中函数中的this指向的是undefined,这也是react里函数式组件里的this为什么指向为undefined原因。
类中的方法会默认开启局部的严格模式
参考资料
标签:
js
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了