構造器模式是最簡單基礎的設計模式,即使用構造器來創建一個對象。
function Person(name, age) {
this.name = name;
this.age = age;
this.toString = () => {
return `this is ${this.name}, ${this.age} years old`
}
}
let latency = new Person('latency', 25);
let cheng = new Person('cheng', 15);
如果考慮到方便繼承,並且不需要讓每個實例都重新定義方法,可以使用基於原型的構造器。
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.toString = function() { // 注意這裏不能用箭頭函數()=>{}
return `this is ${this.name}, ${this.age} years old`
}
let latency = new Person('latency', 25);
let cheng = new Person('cheng', 15);