先讲一下上一章 构造器模式 缺点
function createObj(name, age) {
this.name = name;
this.age = age;
this.getInfo = function () {
console.log(`我叫${this.name},今年${this.age}岁`);
};
}
const ming = new createObj("小明", 18);
const mei = new createObj("小美", 19);
ming.getInfo();
mei.getInfo();
使用 原型模式 优化
function createObj2(name, age) {
this.name = name;
this.age = age;
}
createObj2.prototype.getInfo = function () {
console.log(`我叫${this.name},今年${this.age}岁`);
};
const mu = new createObj2("小木", 18);
const lin = new createObj2("小林", 19);
mu.getInfo();
lin.getInfo();
使用 ES6 class 实现
class studentObj {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
console.log(`我叫${this.name},今年${this.age}岁`);
}
}
const s1 = new studentObj("小火", 22);
const s2 = new studentObj("小炎", 21);
console.log(s1, s2);
s1.getInfo();
s2.getInfo();
注意:在 class 类中,内部方法 getInfo 其实是挂载在 实例中的 prototype 上的。