使用建構式自定義原型
| 12
 3
 4
 5
 6
 7
 8
 
 | function Dog(name, color, size) {this['name'] = name;
 this['color'] = color;
 this['size'] = size;
 };
 
 var Bibi = new Dog('比比', '棕色', '小');
 console.log(Bibi);
 
 | 

透過 new 的運算子每次都會產生一個新的物件。
在上圖可以看到後面用 new 建構出來的 Bibi 原型是指向 Dog 的。
新增一個原型的方法
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | function Dog(name, color, size) {this['name'] = name;
 this['color'] = color;
 this['size'] = size;
 };
 
 var Bibi = new Dog('比比', '棕色', '小');
 var Pupu = new Dog('噗噗', '白色', '大');
 
 Dog.prototype.bark = function () {
 console.log(this.name + ' 吠叫');
 };
 
 console.log(Bibi.bark());  // 比比 吠叫
 console.log(Pupu.bark());  // 噗噗 吠叫
 
 | 

這邊可以看到Dog作為原型,能夠讓實體共用原型的屬性及方法,所以我們在Dog裡面新增一個方法就能夠讓下面的實體共用囉!
這樣的好處是能夠減少記憶體的消耗,因為原型的方法能夠讓下面的實體共用。