JS实现继承的常用方法

1、构造函数继承


   function Parent(name){
       this.name=name;
    }
   Parent.prototype.saiHi=function(){
        console.log("hello")
    }
   function child(name,age,gender){
          Parent.call(this,name) //call改变了this指向,这里指向了 child
                                                                      
           this.age=age
           this.gender=gender
   }

    let child=new Child("王磊",20,"")
    console.log(child.name);// 王磊
    child.sayHi(); // Uncaught TypeError:child.sayHi is not a function
 



缺点:只能解决属性的继承,使用属性的值不重复,但是父级类别的方法不能继承

2、原型链继承

 function Parent(name,gender){
            this.name=name;
            this.gender=gender;
            this.list=[1,2,3]
        }
        Parent.prototype.eat=function(){
            console.log("晚餐时间到")
        }
        function Child(age){
            this.age=age;
        }
        Child.prototype=new Parent("李白","");
        var child=new Child(20);
        var child2=new Child(30);
        child.eat();
        console.log(child.list,child2.list);// [1,2,3] [1,2,3]
        child.list.push(4)
        console.log(child.list);// [1,2,3,4]        
        console.log(child2.list);// [1,2,3,4]

缺点:因为Child的原型对象都是New Parent,所以实例化出来的对象的属性都是一样的,而且Parent上面的引用类型只要有一个实例对象修改了,其他也会跟着修改.因为他们原型对象都是共用的

3、组合继承

function Person(school){
            this.school=school;
        }
        Person.prototype.skill=function(){
            console.log("学习");
        }
        function Student(school,name,age,gender){
            Parent.call(this,school);
            this.name=name;
            this.age=age;
            this.gender=gender;
        }
        Student.prototype=Person.prototype;
        let student=new Student("广铁一中","王菲菲",14,"");
        console.log(Student.prototype===Person.prototype)
        console.log(student.constructor)

缺点:父类的原型对象调用了两次,没有必要,而且student实例的构造函数是来自于Person

原文地址:https://www.cnblogs.com/xxflz/p/12547298.html