实现继承有哪些方式?

1.原型链继承

 function Person(username, userage) {
      this.username = username;
      this.userage = userage
    }
    Person.prototype.sayhi = function () {
      console.log('会说话哦');
    }
    function Student(name, age) {
      this.name = name;
      this.age = age
    }
    Student.prototype = new Person()
    const zs = new Student('zs', 15)

优点:复用父类的方法

缺点:子类实例没有自己的属性

2.构造函数继承

    function Person() {
      this.enjoy = ['看电视', '睡觉']
    }
    function student(id) {
      this.id = id
      Person.call(this) // 改变person的this指向,
                        // 变成student的实例对象,
                        // 因此student就有了Person的enjoy属性
    }

优点:子类每个实例都有自己的属性,不会相互影响

缺点:父类的方法没有办法得到复用

3.组合式继承(原型继承与构造函数继承的结合)

    function Person(username, userage) {
      this.username = username;
      this.userage = userage
    }
    Person.prototype.sayhi = function () {
      console.log('会说话哦');
    }
    function Student(username, userage) {
      Person.call(this, username,userage);
    }
    Student.prototype = new Person()
    const zs = new Student('zs', 15)
    zs.sayhi()
    console.log(zs.username, zs.userage)

优点:继承了前两种方法,复用的傅雷方法又有各自的属性

缺点:内存浪费 

4.寄生组合式继承

    function Person(username, userage) {
      this.username = username;
      this.userage = userage
    }
    Person.prototype.sayhi = function () {
      console.log('会说话哦');
    }
    function Student(username, userage) {
      Person.call(this, username, userage);
    }
    Student.prototype = Object.create(Person.prototype); // object.create()会创造一个对象
                                                     // 新对象的--prototype--会指向传入的参数
    const zs = new Student('zs', 15)
    zs.sayhi()
    console.log(zs.username, zs.userage)

5.ES6继承   

    class Person {
      constructor(name, age) {
        this.name = name
        this.age = age
      }
      sayhi() {
        console.log('会打招呼')
      }
    }
    class student extends Person {
      constructor(name, age,lesson) {
        super(name,age) // 触发调用父构造函数
        this.lesson=lesson
      }
    }
    var stu1=new student('zs',18,11)
    console.log(stu1.name,stu1.age,stu1.lesson)

上一篇:[react] 为什么建议setState的第一个参数是callback而不是一个对象呢?


下一篇:react笔记