js中的继承

/**目前我们有几种方式来实现继承,
     * 方式一:通过原型链的方式来继承
     * 方式二:通过借用构造函数的方式来继承
     * 方式三:组合继承
     * */

    //方式一
    //这种方式存在一些问题,就是不能在实例化子类对象的时候自定义继承过来的属性
    //完全是由改变子类构造函数的原型指向的那个父类的实例化对象来决定
    // function Person(name) {
    //     this.name = name
    // }
    // Person.prototype.eat = function () {
    //     console.log(this.name);
    //     console.log("我喜欢吃东西");
    // }
    //
    // function Student(age) {
    //     this.age = age
    // }
    // Student.prototype = new Person("bar")
    // Student.prototype.study = function () {
    //     console.log("我喜欢学习,好开心");
    // }
    //
    // const stu1 = new Student(18)
    // stu1.eat()
    // stu1.study()

    //方式二
    //这种方式虽然解决了自定义属性的问题,但是并没有继承原型之中的数据
    // function Person(name) {
    //     this.name = name
    // }
    // Person.prototype.eat = function () {
    //     console.log(this.name);
    //     console.log("我喜欢吃东西");
    // }
    //
    // function Student(name, age) {
    //     Person.call(this,name)
    //     this.age = age
    // }
    // const stu2 = new Student("李四", 19)
    //下面这串代码会报错
    // stu2.eat()

    //方式三
    function Person(name) {
        this.name = name
    }
    Person.prototype.eat = function () {
        console.log(this.name);
        console.log("我喜欢吃东西");
    }
    
    function Student(name, age) {
        Person.call(this, name)
        this.age = age
    }
    Student.prototype = new Person()

    const stu3 = new Student("王五", 20)
    stu3.eat()

  

posted @ 2020-12-17 23:04  coderLsq  阅读(26)  评论(0)    收藏  举报