1. 程式人生 > >JavaScript建構函式和prototype

JavaScript建構函式和prototype

建構函式和prototype

  • 約定的建構函式以大寫字母開始
  • 建構函式沒有返回值
  • 使用new產生物件
  • 給建構函式的物件新增方法

如下的建構函式:

var Rectangle = function(a, b) {
    this.x = a;
    this.y = b;
}

如果使用下面這種方式定義方法,只能給物件新增方法:


var p = new Rectangle(1,1);
p.len = function() {
    return 2*(this.x + this.y);
}

需要使用prototype給類新增方法,這樣初始化的物件都擁有方法:

Rectangle.prototype.
len2=function() { return 2*(this.x+this.y); } var p2 = new Rectangle(1,1);