构造器模式是最简单基础的设计模式,即使用构造器来创建一个对象。
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);