DIV CSS 佈局教程網

JavaScript 類別的使用:建構函式、私有屬性與原型繼承
編輯:JavaScript基礎知識     

JavaScript 並不像 Java 那樣原生支援類別(在 ES6 之前更是如此),但我們可以用建構函式與原型模擬出類別的行為。

以建構函式建立類別

function className(prop_1, prop_2, prop_3) {
  this.prop1 = prop_1;
  this.prop2 = prop_2;
  this.prop3 = prop_3;
}

有了這個「類別」,就能建立實例:

var obj_1 = new className(v1, v2, v3);
var obj_2 = new className(v1, v2, v3);

要為類別加上方法(method),其實就是在函式裡再定義函式:

function className(prop_1, prop_2, prop_3) {
  this.prop1 = prop_1;
  this.prop2 = prop_2;
  this.prop3 = prop_3;

  this.func = function new_meth(property) {
    // coding here
  };
}

屬性存取範圍:如何做出私有屬性

在 JavaScript 裡,物件的屬性預設都是全域可見的,也就是物件內外都能直接存取。上面範例中的 this.prop1、this.prop2、this.prop3 都屬於這種公開屬性。

那要如何定義私有屬性呢?答案是使用 var。下面的範例中,price 就變成了私有屬性:

function Car(listedPrice, color) {
  var price = listedPrice;      // 私有屬性
  this.color = color;           // 公開屬性
  this.honk = function () {
    console.log("BEEP BEEP!!");
  };
}

如果想從外部取得私有屬性的值,可以在物件內部加一個方法來回傳它——因為這個方法處在物件的閉包中,所以能存取到私有屬性:

this.getPrice = function () {
  return price;    // 注意這裡不能寫 this.price
};

這個技巧之所以成立,靠的正是閉包:方法保留了對建構函式區域變數的參照,外部則只能透過方法這個受控入口取得資料,無法直接改寫。它也是所謂「定製造函式模式」的基礎。

繼承

使用下面的語法進行繼承:

ElectricCar.prototype = new Car();

並用 instanceof 檢查物件是否繼承自某個類別,回傳 true 或 false:

myElectricCar instanceof Car

為繼承後的物件加上方法:

// 使用建構函式定義新的物件
function ElectricCar(listedPrice) {
  this.electricity = 100;
  var price = listedPrice;
}

// 讓新物件繼承 Car
ElectricCar.prototype = new Car();

// 為新物件加上方法
ElectricCar.prototype.refuel = function (numHours) {
  this.electricity = +5 * numHours;
};

重寫原型上的值或方法

繼承原型之後,我們同時也繼承了原型上的值與方法。但子類別常常需要不同的行為,這時只要重新定義同名的方法即可覆寫:

function Car(listedPrice) {
  var price = listedPrice;
  this.speed = 0;
  this.numWheels = 4;

  this.getPrice = function () {
    return price;
  };
}

Car.prototype.accelerate = function () {
  this.speed += 10;
};

function ElectricCar(listedPrice) {
  var price = listedPrice;
  this.electricity = 100;
}
ElectricCar.prototype = new Car();

// 重寫 accelerate 方法
ElectricCar.prototype.accelerate = function () {
  this.speed += 20;
};

// 加上新方法
ElectricCar.prototype.decelerate = function (secondsStepped) {
  this.speed -= 5 * secondsStepped;
};

myElectricCar = new ElectricCar(500);

myElectricCar.accelerate();
console.log("myElectricCar has speed " + myElectricCar.speed);
myElectricCar.decelerate(3);
console.log("myElectricCar has speed " + myElectricCar.speed);

兩個必須知道的細節

第一,覆寫 prototype 時要補回 constructor。ElectricCar.prototype = new Car() 這行等於換掉整個原型物件,原本指向 ElectricCar 的 constructor 也跟著消失,變成指向 Car。若後續程式依賴 constructor 做型別判斷,記得補上 ElectricCar.prototype.constructor = ElectricCar;。

第二,把方法掛在建構函式裡是有代價的。像 accelerate 這種方法,若定義在建構函式內部,每 new 一個物件就會複製一份函式;掛在 prototype 上則所有實例共享同一份。因此除了確實需要存取私有變數的方法之外,其餘方法都應該放在原型上。ES6 的 class 語法本質上就是這套機制的糖衣,理解底層怎麼運作,寫 class 時才不會踩到 these 種原型與 this 的坑。

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