JS?中在嚴格模式下?this?的指向問題
前言
非嚴格模式下的 this 指向可能我們會經常遇到,但是嚴格模式下的 this 指向不是經常碰到,關于嚴格模式下的 this 指向是怎么樣的,都是指向哪些,這篇博文將會很仔細地說清楚。
一、全局作用域中的this
在嚴格模式下,在全局作用域中,this指向window對象。
"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);
二、全局作用域中函數(shù)中的this
在嚴格模式下,這種函數(shù)中的this等于undefined。不是嚴格模式時,這里的this指向window。在react中render()里的this是指向組件的實例對象。注意區(qū)分是render()里的this還是函數(shù)中的this。(這兩個this指向不同,所以沒法在全局作用域的函數(shù)中直接調用this取值)
"use strict"; console.log("嚴格模式"); console.log('在全局作用域中函數(shù)中的this'); function f1(){ console.log(this); } function f2(){ function f3(){ console.log(this); } f3(); } f1(); f2();
三、對象的函數(shù)(方法)中的this
在嚴格模式下,對象的函數(shù)中的this指向調用函數(shù)的對象實例
"use strict"; console.log("嚴格模式"); console.log("在對象的函數(shù)中的this"); var o = new Object(); o.a = 'o.a'; o.f5 = function(){ return this.a; } console.log(o.f5());
四、構造函數(shù)的this
在嚴格模式下,構造函數(shù)中的this指向構造函數(shù)創(chuàng)建的對象實例。
"use strict"; console.log("嚴格模式"); console.log("構造函數(shù)中的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());
五、事件處理函數(shù)中的this
在嚴格模式下,在事件處理函數(shù)中,this指向觸發(fā)事件的目標對象。
"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; } //這段代碼的作用是使被單擊的元素背景色變?yōu)樗{色
六、內聯(lián)事件處理函數(shù)中的this
在嚴格模式下,在內聯(lián)事件處理函數(shù)中,有以下兩種情況:
<button onclick="alert((function(){'use strict'; return this})());"> 內聯(lián)事件處理1 </button> <!-- 警告窗口中的字符為undefined --> <button onclick="'use strict'; alert(this.tagName.toLowerCase());"> 內聯(lián)事件處理2 </button> <!-- 警告窗口中的字符為button -->
七、定時器中的this,指向的是window
<script> 'use strict' setTimeout(function(){ console.log(this); },1000) </script> //Window {window: Window, self: Window, document: document, name: '', location: Location, …}
注意:嚴格模式全局作用域中函數(shù)中的this指向的是undefined,這也是react里函數(shù)式組件里的this為什么指向為undefined原因。
類中的方法會默認開啟局部的嚴格模式
參考資料
MDNhttps://developer.mozilla.org...
到此這篇關于JS 中在嚴格模式下 this 的指向 超詳細的文章就介紹到這了,更多相關js this 的指向內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript面向對象知識串結(讀JavaScript高級程序設計(第三版))
最近在看JavaScript高級程序設計(第三版),面向對象一章20多頁,來來回回看了三五遍,每次看的收獲都不一樣2012-07-07