DIV CSS 佈局教程網

搞懂 JavaScript 的 prototype、this 與物件繼承
編輯:JavaScript綜合知識     

JavaScript 的「物件導向」和 Java、C# 不太一樣,它沒有 class 關鍵字,一切靠 prototype 串起來。這篇用可執行的程式碼把幾個核心概念走一遍:用 prototype 建立方法與屬性、靜態成員、原型繼承、子類覆寫,以及最容易被誤解的 constructor。

一、把函式變成建構式,為物件建立方法與屬性

var Name = function () {

  // 用 prototype 為物件建立方法
  Name.prototype.Add = function (num, title) { };

  // 也可以直接用 this,兩者等價
  this.Way = function (str) { };

  // 為物件加上屬性
  Name.prototype.xing = "123";

  // 靜態屬性與方法:掛在建構式本身,而不是原型上
  Name.shi = "static";
  Name.Addd = function (num, title) { };

  // 靜態成員只能在靜態的情境裡使用
  alert(Name.shi);
  Name.Addd(1, 2);
}

// 函式也可以這樣宣告
function Name1() {
  Name1.prototype.add = function () { };
  this.way = function () { };
  Name1.prototype.shu = "other";
}

// 定義在函式外面的靜態屬性與方法,全域通用
Name.sha = "static";
Name.Addd2 = function () { };
alert(Name.sha);
Name.Addd2();

var name = new Name();
name.Add();          // 由物件呼叫方法
name.Way();
alert(name.xing);    // 由物件呼叫屬性

三條規則要記牢:定義在函式外的靜態變數全域可呼叫;定義在函式內的靜態變數與方法僅限函式內使用;實例物件不能呼叫靜態方法,也不能使用 prototype。

至於 prototype 上的方法與 this 上的方法有什麼差別?掛在 prototype 上的方法由所有實例共用一份,記憶體較省;用 this 建立的則是每個實例各自一份。物件數量多時,這個差別會很明顯。

二、原型繼承

// 父類
function Class() {
  this.name = "name";
  this.method = function () { alert("method"); };
}

// 子類
function Class1() {
  this.name1 = "name1";
  this.method1 = function () { alert("method1"); };
}

// 子類繼承父類的語法:子類.prototype = new 父類();
Class1.prototype = new Class();

var obj = new Class1();
alert(obj.name);     // name     ← 繼承來
alert(obj.name1);    // name1    ← 自己的
obj.method();        // method
obj.method1();       // method1

三、子類覆寫父類

function Class2() {
  this.name2 = "name2";
  this.method2 = function () { alert("method2"); };
}

Class2.prototype = new Class();                  // 繼承
Class2.prototype.name = "updateName";            // 覆寫父類屬性
Class2.prototype.method = function () {          // 覆寫父類方法
  alert("UpdateMethod");
};

var obj2 = new Class2();
alert(obj2.name);    // updateName
obj2.method();       // UpdateMethod
alert(obj2.name2);   // name2
obj2.method2();      // method2

四、大括號裡的就是物件

var arr = new Array();
arr.push({ "name": "1", "age": 12, funA: function () { } });
arr.push({ "name": "2", "age": 13 });
arr.push({ "name": "3", "age": 14 });

for (var i = 0; i < arr.length; i++) {
  alert(arr[i].name);
  alert(arr[i].age);
}

// 一個物件也可以這樣定義
var newObject = {
  "name": "Jim",
  "sex":  "Man",
  Way: function () { }
};

五、最容易搞混的 constructor

constructor 始終指向「建立當前物件的建構式」:

arr = [1, 56, 34, 12];
console.log(arr.constructor === Array);        // true

Foo = function () { };
console.log(Foo.constructor === Function);     // true
obj = new Foo();
console.log(obj.constructor === Foo);          // true

但只要你覆寫(不是修改)prototype,constructor 就會指向錯的地方:

Person = function (name) { this.name = name; };
Person.prototype = {                    // 整個覆寫
  getName: function () { return this.name; }
};
p = new Person();
console.log(p.constructor === Person);          // false!

原因是覆寫 Person.prototype 等同於這樣做:

Person.prototype = new Object({
  getName: function () { return this.name; }
});

而 constructor 指向建立自身的建構式,此時變成 Object。修正方式很簡單,補一行把它扶正:

Person.prototype = {
  getName: function () { return this.name; }
};
Person.prototype.constructor = Person;   // 補回來

六、this 是執行期才決定的

this 指代什麼,取決於「這個函式在執行時是被哪個物件呼叫」,而不是它定義在哪裡。同一個函式,用 foo() 呼叫時 this 是 window,用 pack.foo() 呼叫時 this 就是 pack。apply 與 call 兩個全域方法可以強制改變 this 的指向,兩者唯一差別在參數傳遞形式。因為函式在 JavaScript 中也是物件,所以連函式屬性上的方法都能各自有自己的 this——這正是那些奇怪的 this 問題的來源。

附帶一個 prototype 的陷阱

幫 Array 擴充方法後,for-in 會把這個方法也遍列出來:

Array.prototype.min = function () { /* ... */ };
arr = [1, 56, 34, 12];
total = 0;
for (var i in arr) {
  total += parseInt(arr[i], 10);   // NaN,因為 i 也可能是 "min"
}

解法是用 hasOwnProperty 過濾:

for (var i in arr) {
  if (arr.hasOwnProperty(i)) {
    total += parseInt(arr[i], 10);
  }
}

理解 prototype 之後,ES6 的 class 語法就只是糖——底下一樣是原型鏈。把這篇的順序跑一遍,再回頭看 class,會清楚很多。

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