DIV CSS 佈局教程網

JavaScript 的四種函式呼叫模式與 this 綁定規則
編輯:關於JavaScript     

談 this 之前,得先理解一件事:在 JavaScript 中,函式怎麼被呼叫,決定 this 指向誰。一般會把呼叫方式歸成四類,其中「作為普通函式呼叫」是最容易搞錯的一種。

一、方法呼叫模式

函式作為某個物件的屬性、並以 物件.函式() 的形式被呼叫時,this 指向該物件。

 var obj = {
  fun1: function(){
    console.log(this);   // 指向 obj
  }
};
obj.fun1();   // 方法呼叫

二、建構器呼叫模式

以 new 呼叫函式時,this 會指向新建立的物件實例。

 function Person(name, age, job){
  this.name = name;
  this.age = age;
  this.job = job;
  this.sayName = function(){
    alert(this.name);
  };
}

var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

三、apply/call 呼叫模式

這兩者讓你手動指定 this 的歸屬,是動態改變上下文的正式工具。

 function cat(){}
cat.prototype = {
  food: "fish",
  say: function(){
    alert("I love " + this.food);
  }
};

var blackCat = new cat();
blackCat.say();   // I love fish

這裡若沒有顯式的 return,新物件會被隱式回傳並成為建構結果,等同於寫成 new cat()。

接著看它的用處。假設我們另有一個物件:

 var whiteDog = { food: "bone" };

我們不想替 whiteDog 重新定義 say 方法,此時就能借用 blackCat 的:

 blackCat.say.call(whiteDog);   // I love bone

由此可見,call 與 apply 是為了「動態改變 this」而存在的:當某個物件本身沒有某方法,而別的物件有,就能借來用。

最實用的場景之一,是把類陣列物件轉成真陣列。透過 getElementsByTagName 選到的節點集合,以及函式裡的 arguments,都屬於 array-like,沒有 push、pop、slice 等方法可用:

 var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
// 之後就能使用 Array 的所有方法

ES6 之後有更直白的寫法:Array.from(...) 或展開運算子 [...nodeList]。

四、普通函式呼叫模式

直接寫 fun() 這種形式,在非嚴格模式下 this 會指向全域物件 window;在嚴格模式('use strict')下則是 undefined。這是最容易踩坑的一種,因為很多「我以為 this 指向某物件,結果卻是 window」的 bug 都源自這裡。

 function show(){ console.log(this); }
show();   // 非嚴格模式:Window;嚴格模式:undefined

// 常見陷阱:方法內的巢狀函式會斷掉 this
var counter = {
  count: 0,
  inc: function(){
    setTimeout(function(){
      this.count++;   // 這裡的 this 不是 counter!
    }, 100);
  }
};

解法是用箭頭函式保留外層 this,或先把 this 存成 self/that 再用,或直接 bind(counter)。

把四種模式記牢,再搭配箭頭函式「this 由定義位置決定、不被呼叫方式改寫」的特性,絕大多數 this 相關的困惑都能收斂。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved