1. 程式人生 > >【JavaScript中的this詳解】

【JavaScript中的this詳解】

定律 htm uid js代碼 tdd ati tom dmr doctype

前言

this用法說難不難,有時候函數調用時,往往會搞不清楚this指向誰?那麽,關於this的用法,你知道多少呢?

下面我來給大家整理一下關於this的詳細分析,希望對大家有所幫助!

this指向的規律

this指向的規律往往與函數調用的方式息息相關;this指向的情況,取決於函數調用的方法有哪些。

我們來看一下姜浩五大定律:

姜浩五大定律:

①通過函數名()直接調用:this指向window;
②通過對象.函數名()調用的:this指向這個對象;
③函數作為數組的一個元素,通過數組下標調用的:this指向這個數組;
④函數作為window內置函數的回調函數調用:this指向window,setTimeout,setInterval等……;

⑤函數作為構造函數,用new關鍵字調用時:this指向新new出的對象。

對於this指向誰,我們記住一句就行:誰最終調用函數,this就指向誰!

因為,

①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的用法,你掌握了麽?

今天的內容就先分享到這裏,希望可以幫到你~如有問題,歡迎留言評論,大家一起交流,一起進步!

技術分享


作者:夕照希望
出處:http://www.cnblogs.com/hope666/

【JavaScript中的this詳解】