1.原型继承,简单,但是原型对象的所有属性被所有实例共享,例如子类对color进行修改,其他的也会变。
function Parent(name, age){
this.name = name;
this.age = 24;
this.getName = function (){
return this.name;
};
this.color = ['ff','22'];
}
Parent.prototype.getAge = function (){
return this.age;
}
function Son(name){
this.name = name;
}
Son.prototype = new Parent();
let son1 = new Son('one');
let son2 = new Son('two');
son1.color.push('333');
console.log(son2.name);
console.log(son1.color);//["ff", "22", "333"]
console.log(son2.color);//["ff", "22", "333"]
2.构造函数继承,只会继承实例属性,不会继承原型属性
function Parent(name,age){
this.name = name;
this.age = age;
this.getAge = function(){
return this.age;
}
}
Parent.prototype.getName = function(){
return this.name;
}
Parent.prototype.sex = '男';
function Son(name,sex){
this.name = name;
this.sex = sex;
Parent.call(this, name ,24);
}
let son = new Son('小仙女','女');
console.log(son.name);
console.log(son.sex);
console.log(son.getAge());
console.log(son.getName()); // undefined
- 组合继承,会继承原型和实例的属性,但是会两次调用Parent,生成两份父类实例
function Parent(name,age){
this.name = name;
this.age = age;
this.getAge = function(){
return this.age;
}
}
Parent.prototype.getName = function(){
return this.name;
}
Parent.prototype.sex = '男';
function Son(name,sex,age){
this.name = name;
this.sex = sex;
Parent.call(this, name ,age);
}
Son.prototype = new Parent();
let son = new Son('小仙女','女',22);
console.log(son.name);
console.log(son.sex);
console.log(son.getAge());
console.log(son.getName());
- 寄生组合继承,比较完美
function Parent(name,age){
this.name = name;
this.age = age;
this.getAge = function(){
return this.age;
}
}
Parent.prototype.getName = function(){
return this.name;
}
Parent.prototype.sex = '男';
function Son(name,sex,age){
this.name = name;
this.sex = sex;
Parent.call(this, name ,age);
}
//复制一份父原型,Son的prototype指向复制的父,constructor指向Son构造函数
Son.prototype = Object.create(Parent.prototype);
Son.prototype.constructor = Son;
let son = new Son('小仙女','女',22);
console.log(son.name);
console.log(son.sex);
console.log(son.getAge());
console.log(son.getName());