DIV CSS 佈局教程網

用實例解析 JavaScript 的面向物件
編輯:JavaScript基礎知識     

1. 類結構剖析

function fn() {
  var variable = "";        // 靜態屬性
  function method() {};     // 靜態方法
  this.propertyName = value; // 特定屬性
  this.method = function () {}; // 特定方法
}

靜態屬性和靜態方法用於函數 fn 內部,無法被外界存取;而特定屬性和特定方法是函數被 new 之後所建立物件應有的屬性和方法,因此可以被外界存取。若沒有 new 關鍵字,則會被當作普通函數呼叫,此時 this 指向 window 物件。

此外,也可以直接這樣寫:fn.propertyName 或 fn.method = function () {},這就好比 Java 中類的靜態變數。在 JS 裡,new 出來的子物件無法使用類的成員變數。

2. 矩形類

function Rect(width, height) {
  this.r_width = width;
  this.r_height = height;
  this.desc = function () {
    return '我是一個矩形哦';
  };
}

// 擴展矩形計算面積的方法
Rect.prototype.getArea = function () {
  return this.r_width * this.r_height;
};

// 列印結果的函數
Rect.prototype.toString = function () {
  alert("這個矩形的面積是:" + this.getArea() + ",寬度是:" + this.r_width + ",高度是:" + this.r_height);
};

3. 平行四邊形類

function Square(value) {
  this.s_width = value;
  this.s_height = value;
}

// 寫法一:直接把 Rect 的 prototype 賦給 Square
// 拿不到 Rect 的特有屬性和方法,且會覆蓋 Square 原有的擴展
Square.prototype = Rect.prototype;

// 寫法二:透過 new 繼承
// 能拿到 Rect 特有的屬性、方法,還包括其原型鏈上的東西
Square.prototype = new Rect();

寫法二比較完整,但要注意 Square.prototype 容易被覆蓋的問題,建議把擴展寫在後面:

Square.prototype.say = function () {
  return "我是一個平行四邊形";
};

// 也可以覆蓋繼承過來的屬性和方法
Square.prototype.getArea = function () {
  return this.s_width * this.s_height;
};
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved