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