當 code 愈寫愈多了之後,會愈感覺 OO 的重要性呀!

雖然我沒有很認真研究 JavaScript 的 type checking 或是 memory allocation 的機制,不過目前這樣做還能動,而且也還蠻好理解的。

只用一次的 object

那就使用 JSON,比方說:

var rect = {
  left: 10,
  top: 10,
  width: 50,
  height: 50,
  area: function() {
    return this.width * this.height;
  }
};

rect.width = 100; // change the width to 100
alert(rect.area());  // calculate the area of the rectangle.

除了放一般的變數外,也可以放 function,當然也可以 JSON 裡面又有 JSON。

定義成 class,可生成許多 instance

假如我們要宣告一個 Rectangle 的 class,上述的例子就可以寫成這樣:

function Rectangle(l, t, w, h) {
    this.left = l;
    this.top = t;
    this.width = w;
    this.height = h;
}

Rectangle.prototype.area = function() {
  return this.width * this.height;
}

var r = new Rectangle(10, 10, 50, 50);
alert(r.area());

定義一個與類別同名的 function 作為 constructor,然後 member function 就加一個 prototype 的宣告法,如此便可以使用 new 來產生一個 class 的 instance 了!當然也可以利用 JSON 寫成這樣:

Rectangle = function ( ... ) { .... }
Rectangle.prototype = {
  area: function() {
    return this.width * this.height;
  },

  setWidth: function(width) {
    this.width = width;
  },
  ...
  ...
}

如果要使用繼承,就利用 Object.extend 方法:

Square = function ( ... ) { .... }
Square.prototype = Object.extend(new Rectangle(...), {
  area: function() {
    return this.width * this.width;
  }
  ...
});

其實 JavaScript 的 OOP 也沒有很難懂就是了,目前只研究到這裡,之後有發現其它 OOP 特性再來作筆記吧!

 

歷史上的今天