JavaScript 的继承

    xiaoxiao2025-03-02  32

    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、组合继承

    //原型实现继承 //借用构造函数实现继承 //组合继承:原型继承+借用构造函数继承 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、拷贝继承

    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();

     

    最新回复(0)