JavaScript設計模式---構造器模式

構造器模式是最簡單基礎的設計模式,即使用構造器來創建一個對象。

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章