DIV CSS 佈局教程網

JavaScript 普通函數與構造函數的區別詳解
編輯:JavaScript綜合知識     

什麼是構造函數?它和普通程序函數差在哪?寫 new 的時候引擎究竟做了什麼?構造函數有返回值怎麼辦?能不能當普通函數調用?這幾個問題串起來,基本就覆蓋了面試中關於函數的高頻考點。

先說 this

this 永遠指向當前正在執行的函數或方法的 owner。

function test() { console.log(this); }
test();   // Window,函數定義在全局時 owner 就是當前頁面

this 指向的四種典型情況:

  1. 全局中調用:this 指向 window 對象。
  2. 函數調用:test() 內部的 this 依然指向 window。
  3. 對象方法調用:obj1.fn() 中的 this 指向 obj1。
  4. 構造函數調用:var dog = new Dog() 中的 this 指向新創建的實例。

call 與 apply

兩者作用相同,只是接收參數的方式不同:call 接受多個單獨參數,apply 接受參數數組。

它們的價值在於「借方法」:當一個對象缺少某個方法時,可以借用其他對象的現成方法,方式是把它運行時的 this 替換成自己。

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

var dog = new Dog();
dog.bark("有小偷");                      // 汪汪汪 有小偷

var cat = { sound: '喵喵喵' };
Dog.prototype.bark.call(cat, "餓了");     // 喵喵喵 餓了

這裡 cat 完全沒有 bark 方法,卻能借到 Dog 的實現,且不產生任何耦合。

普通函數的四個特點

1. 不需要 new

function fn() { alert("hello sheila"); }
fn();

2. 可以用 return 返回值

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

3. 內部不建議使用 this。因為此時 this 指向 window,無意間會往全局掛變量:

function greeting() {
  this.name = "sheila";
  alert("hello " + this.name);
}
greeting();
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
Prince.age;         // undefined,不能用類型名訪問實例屬性

1. 用 new 調用。

2. 內部 this 指向新實例。用 this 定義的是實例成員,必須通過實例訪問。

3. 默認不需要 return。構造函數默認返回 this,也就是新實例。

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

new 背後的四步

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

  1. 創建一個空對象:var prince = {}
  2. 把構造函數中的 this 指向這個新對象。
  3. 讓新對象的 __proto__ 指向構造函數的 prototype,建立對象與原型之間的鏈接。
  4. 執行構造函數內的代碼,完成屬性初始化。

構造函數裡寫 return 會怎樣

分兩種情況:

返回五種簡單類型(String、Number、Boolean、Null、Undefined)時,返回值被忽略,仍然返回 this 對象。

返回對象時,this 被拋棄,直接返回 return 後面的那個對象。

function Person(name) {
  this.name = name;
  return { name: "cherry" };
}
var person = new Person("sheila");
person.name;    // cherry,而不是 sheila

這是一個很容易導致難以排查的 bug 的行為,實戰中構造函數裡請不要寫 return。

最後補充:ES6 的 class 語法本質上就是構造函數的語法糖,用 class 定義的「構造函數」若不加 new 直接調用會直接報錯,比傳統寫法更安全。

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