1. 程式人生 > >組合使用構造函數模式和原型模式

組合使用構造函數模式和原型模式

創建 類型 prototype 原型 構造函數 == pro name 自定義

創建自定義類型的最常見方式,就是組合使用構造函數與原型模式。構造函數模式用於定義實例屬性
而原型模式用於定義方法和共享方法,結果,每個實例都會有自己的一份實例屬性
的副本,但同時又共享著對方法的引用,最大限度地節省了內存,另外這種模式還支持像構造函數傳遞參數

function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.firend = [‘ahao‘,‘ada‘];
}
Person.prototype = {
constructor: Person,
sayName:function(){
console.log(this.name);
}
};
var p1 = new Person(‘wh‘,24,‘web開發‘);
var p2 = new Person(‘lsf‘,47,‘超市上班‘);

p1.firend.push(‘asong‘);
console.log(p1.firend); // ["ahao", "ada", "asong"]
console.log(p2.firend); // ["ahao", "ada"]
console.log(p1.firend === p2.firend); // false
console.log(p1.sayName === p2.sayName); // true

  



在這個例子中,實例屬性都是構造函數中定義的,而由所有實例共享的屬性constructor和方法
sayName()則是在原型中定義的,而修改了p1.friend,並不會影響p2,因為它們分別引用了不同的數組。
這種構造函數與原型混成的模式,是目前使用最廣泛的,認同度最高的一種創建自定義類型
的方法

組合使用構造函數模式和原型模式