前言html
this用法說難不難,有時候函數調用時,每每會搞不清楚this指向誰?那麼,關於this的用法,你知道多少呢?數組
下面我來給你們整理一下關於this的詳細分析,但願對你們有所幫助!ide
this指向的規律函數
this指向的規律每每與函數調用的方式息息相關;this指向的狀況,取決於函數調用的方法有哪些。ui
咱們來看一下姜浩五大定律:this
①經過函數名()直接調用:this指向window;
②經過對象.函數名()調用的:this指向這個對象;
③函數做爲數組的一個元素,經過數組下標調用的:this指向這個數組;
④函數做爲window內置函數的回調函數調用:this指向window,setTimeout,setInterval等……;
⑤函數做爲構造函數,用new關鍵字調用時:this指向新new出的對象。spa
對於this指向誰,咱們記住一句就行:誰最終調用函數,this就指向誰!code
由於,htm
①this指向的永遠只多是對象!
②this指向誰,永遠不取決於this寫在哪!而是取決於函數在哪調用!!!
③this指向的對象,咱們稱之爲函數的上下文context,也叫函數的調用者。對象
多說無益,理論不如實踐,你們一塊兒來看下面的代碼:
HTML代碼:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>JavaScript中的this詳解</title> 6 </head> 7 8 <body> 9 <div id="div">1111</div> 10 </body> 11 </html>
JS代碼:
1 function func(){ 2 console.log(this); 3 } 4 5 //①經過函數名()直接調用:this指向window 6 func(); 7 8 //②經過對象.函數名()調用的:this指向這個對象 9 //狹義對象 10 var obj = { 11 name:"obj", 12 func1:func 13 }; 14 15 obj.func1();//this--->obj 16 17 //廣義對象 18 document.getElementById("div").onclick = function(){ 19 this.style.backgroundColor = "red"; 20 };//this--->div 21 22 //③函數做爲數組的一個元素,經過數組下標調用的:this指向這個數組 23 var arr = [func,1,2,3]; 24 arr[0](); //this--->數組arr 25 26 //④函數做爲window內置函數的回調函數調用:this指向window 27 setTimeout(func,1000); 28 //setInterval(func,1000); 29 30 //⑤函數做爲構造函數,用new關鍵字調用時:this指向新new出的對象 31 var obj = new func();//this--->new出的新obj
看過代碼以後,對於this的指向及用法,你瞭解透徹了麼?
下面咱們來作個小練習鞏固一下this指向的五大定律。
看代碼↓↓↓:
HTML代碼:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>JavaScript中的this詳解</title> 6 </head> 7 8 <body> 9 <div id="div">1111</div> 10 </body> 11 </html>
JS代碼:
1 var obj1 = { 2 name:'obj1', 3 arr:[setTimeout(func,3000),1,2,3] 4 } 5 document.getElementById("div").onclick = obj1.arr[0]; 6 //函數最終調用者:setTimeout,符合規律⑤ this--->window 7 8 9 var obj2 = { 10 name:'obj1', 11 arr:[func,1,2,3] 12 } 13 document.getElementById("div").onclick = obj2.arr[0](); 14 //函數最終調用者:數組下標,符合規律③ this--->arr 15 16 17 var obj3 = { 18 name:'obj1', 19 arr:[{name:'arrObj',fun:func},1,2,3] 20 } 21 document.getElementById("div").onclick = obj3.arr[0].fun(); 22 //函數最終調用者:{name:'arrObj',fun:func},符合規律② this--->obj
this的用法,你掌握了麼?
今天的內容就先分享到這裏,但願能夠幫到你~若有問題,歡迎留言評論,你們一塊兒交流,一塊兒進步!