DIV CSS 佈局教程網

普通函數與建構函數的差別:new 關鍵字到底做了什麼
編輯:關於JavaScript     

「建構函數不過就是函數」這句話對,但沒說完。兩者在呼叫方式、this 指向、返回值規則與命名慣例上都有明顯差異。本文把常見的疑問逐一拆開。

先談 this

this 永遠指向「目前正被執行的函式或方法的擁有者(owner)」。以下四種情況最常遇到:

function test() { console.log(this); }
test(); // 在瀏覽器中印出 Window 物件

1. 全域環境中直接執行:this 指向 window。

2. 直接呼叫函式 test():非嚴格模式下 this 同樣指向 window。

3. 作為物件方法呼叫 obj1.fn():this 指向 obj1。

4. 以 new 呼叫建構函數 new Dog():this 指向剛建立出來的新實例。

call 與 apply:借別人的方法來用

兩者效果相同,差別只在參數傳遞形式:call 接受一串獨立參數,apply 接受一個陣列。它們的作用是:當某個物件缺少某個方法時,可以把函式中的 this 替換成該物件,藉此「借用」其他物件現成的方法,實質上是改變函式執行時的上下文。

function Dog() { this.sound = "汪汪汪"; }
Dog.prototype.bark = function (words) { alert(this.sound + " " + words); };

var cat = { sound: '喵喵喵' };

var dog = new Dog();
dog.bark("有小偷");                 // 汪汪汪 有小偷
Dog.prototype.bark.call(cat, "餓了"); // 喵喵喵 餓了

cat 完全沒有自己定義 bark,卻能借用 Dog 的方法,靠的就是 call 把 this 換成 cat。

普通函數的四個特徵

1. 不需要 new 即可呼叫:fn();

2. 可以用 return 回傳值:

function fn(a, b) { return a + b; }
alert(fn(2, 3)); // 5

3. 不建議在函式內部使用 this。因為此時 this 指向 window,用 this 定義變數無異於污染全域:

function greeting() {
  this.name = "sheila";
  alert("hello " + this.name);
}
greeting();          // hello sheila
alert(window.name);  // sheila —— 不知不覺多了一個全域變數

4. 命名慣例為小駝峰(首字母小寫)。

建構函數的四個特徵

function Prince(name, age) {
  this.gender = "male";
  this.kind = true;
  this.rich = true;
  this.name = name;
  this.age = age;
}
Prince.prototype.toFrog = function () {
  console.log("Prince " + this.name + " turned into a frog.");
};

var prince = new Prince("charming", 25);
prince.toFrog();  // Prince charming turned into a frog.
prince.kind;      // true

1. 必須用 new 呼叫。

2. 內部this指向新建立的實例,用 this 掛上去的屬性就是實例屬性,只能透過實例存取:

prince.age;   // 25
Prince.age;   // undefined

3. 預設不需要寫 return,會自動回傳 this(也就是新實例)。

4. 建議首字母大寫,以便和普通函數區分。

new 執行的四個步驟

以 var prince = new Prince("charming", 25); 為例:

第一步,建立一個空物件。var prince = {};

第二步,把建構函數中的 this 指向這個新物件。

第三步,把新物件的 __proto__ 指向建構函數的 prototype,建立物件與原型之間的關係。

第四步,執行建構函數內的程式碼,把屬性與方法掛到新物件上。

建構函數写了 return 會怎樣

沒有顯式 return 時,回傳 this。有寫 return 時分兩種情況:

1. 回傳五種簡單型別(String、Number、Boolean、Null、Undefined):return 值被忽略,仍然回傳 this。

2. 回傳物件:this 被捨棄,改為回傳該物件。

function Person(name) {
  this.name = name;
  return { name: "cherry" };
}
var person = new Person("sheila");
person.name; // "cherry",回傳的是 return 的物件,而非 this

這也是為什麼「建構函數不要隨便回傳物件」是個實務上的 convention——它會讓 instanceof 判斷與原型鏈的預期全部走鐘。

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