1、原型链继承
原型链继承:将父类的实例作为子类的原型,他的特点是实例是子类的实例也是父类的实例,父类新增的原型方法/属性,子类都能够访问,并且原型链继承简单易于实现,缺点是来自原型对象的所有属性被所有实例共享,无法实现多继承,无法向父类构造函数传参。
//js中通过原型来实现继承
function Person(name,age,sex) {
this.name=name;
this.sex=sex;
this.age=age;
}
Person.prototype.eat=function () {
console.log("人有名字");
};
Person.prototype.sleep=function () {
console.log("人要睡觉");
};
Person.prototype.hobby=function () {
console.log("每个人都有自己的爱好");
};
// 创建一个学生对象
function Student(score) {
this.score=score;
}
//改变学生的原型的指向,从而可以让学生和人产生联系,继承人的属性
Student.prototype=new Person("雷胖子",18,"男");
Student.prototype.study=function () {
console.log("胖子的爱好就是学习.");
};
// 实例化这个学生对象
var stu = new Student(60);
console.log("父类person的属性和方法");
console.log(stu.name);
console.log(stu.age);
console.log(stu.sex);
stu.eat();
stu.play();
stu.sleep();
console.log("学生对象中自己有属性");
console.log(stu.score);
stu.study();
2、构造继承
构造继承:使用父类的构造函数来增强子类实例,即复制父类的实例属性给子类,构造继承可以向父类传递参数,可以实现多继承,通过call多个父类对象。但是构造继承只能继承父类的实例属性和方法,不能继承原型属性和方法,无法实现函数复用,每个子类都有父类实例函数的副本,影响性能。
function Person(name, age, sex, weight) {
this.name = name;
this.age = age;
this.sex = sex;
this.weight = weight;
}
Person.prototype.sayHi = function () {
console.log("您好");
};
function Student(name,age,sex,weight,score) {
//借用构造函数
Person.call(this,name,age,sex,weight);
this.score = score;
}
var stu1 = new Student("牛牛",18,"男","60kg","90");
console.log(stu1.name, stu1.age, stu1.sex, stu1.weight, stu1.score);
var stu2 = new Student("老大",17,"男","70kg","80");
console.log(stu2.name, stu2.age, stu2.sex, stu2.weight, stu2.score);
var stu3 = new Student("胖子",21,"男","80kg","60");
console.log(stu3.name, stu3.age, stu3.sex, stu3.weight, stu3.score);
console.log(stu3.sayHi())// 报错
3、组合继承
组合基础:前面已经介绍了 js 中实现继承的两种模式:原型链继承和构造函数继承。但是对于这两种模式都存在各自的缺点,所以,我们可以考虑看看,是否能将这二者结合到一起,从而发挥二者之长。即在继承过程中,既可以保证每个实例都有它自己的属性,又能做到对一些属性和方法的复用。这样就可以避免之前两种继承的缺陷。
//原型实现继承
//借用构造函数实现继承
//组合继承:原型继承+借用构造函数继承
function Person(name,age,sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
Person.prototype.play=function () {
console.log("一起打篮球,走起");
};
function Student(name,age,sex,score) {
//借用构造函数:属性值重复的问题
Person.call(this,name,age,sex);
this.score=score;
}
//改变原型指向----继承
Student.prototype=new Person();//不传值
Student.prototype.eat=function () {
console.log("吃油炸馍");
};
var stu=new Student("康哥",20,"男","89");
console.log(stu.name,stu.age,stu.sex,stu.score);
stu.sayHi();
stu.eat();
var stu2=new Student("金龙",22,"男","98");
console.log(stu2.name,stu2.age,stu2.sex,stu2.score);
stu2.sayHi();
stu2.eat();
//属性和方法都被继承了
4、拷贝继承
拷贝继承:该继承方式是通过把一个对象中的属性或者方法直接复制到另一个对象中,另一个对象就拥有了这个对象的相关属性和方法。 特点:支持多继承 缺点: 1、效率较低,内存占用高(因为要拷贝父类的属性) 2、无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到)
function Person() {
}
Person.prototype.age=10;
Person.prototype.sex="男";
Person.prototype.height=100;
Person.prototype.play=function () {
console.log("一起打球啊");
};
var obj2={};
//Person的构造中有原型prototype,prototype就是一个对象,那么里面,age,sex,height,play都是该对象中的属性或者方法
for(var key in Person.prototype){
obj2[key]=Person.prototype[key];
}
console.dir(obj2);
obj2.play();