1. 程式人生 > 實用技巧 >關於JavaScript中的this指向問題

關於JavaScript中的this指向問題

this是面嚮物件語言中一個重要的關鍵字,理解並掌握該關鍵字的使用對於我們程式碼的健壯性及優美性至關重要。而javascript的this又有區別於Java、C#等純面向物件的語言,這使得this更加撲朔迷離,讓人迷惑。
this使用到的情況:

1. 純函式
2. 物件方法呼叫
3. 使用new呼叫建構函式
4. 內部函式
5. 使用call / apply
6.事件繫結

1. 純函式

var name = 'this is window';  //定義window的name屬性 
function getName(){ 
       console.log(this);    //控制檯輸出: Window  //this指向的是全域性物件--window物件 
       console.log(this.name);  //控制檯輸出: this is window  / 
} 
getName();

執行結果分析:純函式中的this均指向了全域性物件,即window。

2. 物件方法呼叫

var name = 'this is window';  //定義window的name屬性,看this.name是否會呼叫到 
var testObj = { 
    name:'this is testObj', 
    getName:function(){ 
        console.log(this);  //控制檯輸出:testObj   //this指向的是testObj物件 
        console.log(this.name);  //控制檯輸出: this is testObj 
    } 
} 
testObj.getName();

3. 使用new呼叫建構函式

function getObj(){ 
    console.log(this);    //控制檯輸出: getObj{}  //this指向的新建立的getObj物件 
} 
new getObj();  

執行結果分析:new 建構函式中的this指向新生成的物件。

4. 內部函式

var name = "this is window";  //定義window的name屬性,看this.name是否會呼叫到 
var testObj = { 
    name : "this is testObj", 
    getName:function(){ 
        //var self = this;   //臨時儲存this物件 
        var handle = function(){ 
            console.log(this);   //控制檯輸出: Window  //this指向的是全域性物件--window物件 
            console.log(this.name);  //控制檯輸出: this is window   
            //console.log(self);  //這樣可以獲取到的this即指向testObj物件 
        } 
        handle(); 
    } 
} 
testObj.getName();

執行結果分析:內部函式中的this仍然指向的是全域性物件,即window。這裡普遍被認為是JavaScript語言的設計錯誤,因為沒有人想讓內部函式中的this指向全域性物件。一般的處理方式是將this作為變數儲存下來,一般約定為that或者self,如上述程式碼所示。

5. 使用call / apply

var name = 'this is window';  //定義window的name屬性,看this.name是否會呼叫到 
var testObj1 = { 
    name : 'this is testObj1', 
    getName:function(){ 
        console.log(this);   //控制檯輸出: testObj2  //this指向的是testObj2物件 
        console.log(this.name);  //控制檯輸出: this is testObj2   
    } 
} 

var testObj2 = { 
    name: 'this is testObj2' 
} 

testObj1.getName.apply(testObj2); 
testObj1.getName.call(testObj2);

Note:apply和call類似,只是兩者的第2個引數不同:
[1] call( thisArg [,arg1,arg2,… ] ); // 第2個引數使用引數列表:arg1,arg2,...
[2] apply(thisArg [,argArray] ); //第2個引數使用 引數陣列:argArray
執行結果分析:使用call / apply 的函式裡面的this指向繫結的物件。

6. 事件繫結

事件方法中的this應該是最容易讓人產生疑惑的地方,大部分的出錯都源於此。

//頁面Element上進行繫結 
  <script type="text/javascript"> 
     function btClick(){ 
        console.log(this);  //控制檯輸出: Window  //this指向的是全域性物件--window物件 
    } 
  </script> 
  <body> 
    <button id="btn" onclick="btClick();" >點選</button> 
  </body> 
//js中繫結方式(1) 
  <body> 
    <button id="btn">點選</button> 
  </body> 
  <script type="text/javascript"> 
     function btClick(){ 
        console.log(this);  //控制檯輸出:<button id="btn">點選</button>  //this指向的是Element按鈕物件 
     } 

     document.getElementById("btn").onclick = btClick; 
     document.getElementById("btn").onclick();   //預設點選
  </script> 

//js中繫結方式(2) 
<body> 
   <button id="btn">點選</button> 
 </body> 
 <script type="text/javascript"> 
    document.getElementById("btn").onclick = function(){ 
     console.log(this);  //控制檯輸出:<button id="btn">點選</button>  //this指向的是Element按鈕物件 
    } 
    document.getElementById("btn").onclick(); 
 </script> 

//js中繫結方式(3) 
<body> 
   <button id="btn">點選</button> 
 </body> 
 <script type="text/javascript"> 
    function btClick(){ 
        console.log(this);   
     } 

    document.getElementById("btn").addEventListener('click',btClick); //控制檯輸出:<button id="btn">點選</button>  //this指向的是Element按鈕物件把函式(方法)用在事件處理的時候。 
    document.getElementById("btn").attachEvent('onclick',btClick);  //IE使用,控制檯輸出: Window  //this指向的是全域性物件--window物件 
 </script>

執行結果分析:以上2種常用事件繫結方法,在頁面Element上的進行事件繫結(onclick="btClick();"),this指向的是全域性物件;而在js中進行繫結,除了attachEvent繫結的事件方法(this指向的是全域性物件)外,this指向的是繫結事件的Elment元素。