原型链继承,将父类的实例作为子类的原型,他的特点是实例是子类的实例也是父类的实例,父类新增的原型方法/属性,子类都能够访问,并且原型链继承简单易于实现,缺点是来自原型对象的所有属性被所有实例共享,无法实现多继承,无法向父类构造函数传参。
//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();构造继承,使用父类的构造函数来增强子类实例,即复制父类的实例属性给子类,构造继承可以向父类传递参数,可以实现多继承,通过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())// 报错