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原因。

类中的方法会默认开启局部的严格模式

参考资料

MDN https://developer.mozilla.org...


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM