继承之前:
function Women() {
this.eyes = 2;
this.head = 1;
}
const red = new Women();
console.log(red);
function Man() {
this.eyes = 2;
this.head = 1;
}
const pink = new Man();
console.log(pink);
结果:
我们发现两个构造函数之间有许多重复的属性,我们可以抽取出来,放到 prototype 上实现共享。
抽取之后:
function Person () {
eyes: 2,
head: 1
}
function Women() {
}
//将 Person 的实例化对象赋给 Women 的 prototype 属性
Women.prototype = new Person();
//再重新将 prototype 的 constructor 指向Women
Women.prototype.constructor = Women;
const red = new Women();
console.log(red);
function Man() {
}
//将 Person 的实例化对象赋给 Men 的 prototype 属性
Man.prototype = new Person();
//再重新将 prototype 的 constructor 指向Men
Man.prototype.constructor = Man;
const pink = new Man();
console.log(pink);
结果: