1.原型链继承(通过只继承父类原型上的属性,优化了所有实例共享实例引用变量的问题)

// 原型链实现类的继承
     function extend(Children, Parent) {
        // 避免所有的子类引用变量共享问题-引入临时新的构造函数
        function tem(){}
        tem.prototype = Parent.prototype

        Children.prototype = new tem()
        Children.prototype.constructor = Children
    }

// 父类
    function Parent() {this.eyes = 'blue'; this.color=['red','yellow','black']}
    Parent.prototype.size = [1,2]
    Parent.prototype.getEyes = function getEyes() {
        console.log(this.eyes)
    }

    // 子类
    function Children() {}

    // 验证
    extend(Children, Parent)
    let chilren1 = new Children()
    let chilren2 = new Children()

    chilren1.getEyes() // blue

    // 构造函数上的this
    chilren1.color.push('esp')
    console.log('chilren2.color', chilren2.color) // color不存在

2.原型链,构造函数组合继承,寄生组合继承,最优继承

 // 原型链/构造函数组合实现类的继承
     function extend(Children, Parent) {
        // 只是为了继承一个干干净净的原型~~
        function tem(){}
        tem.prototype = Parent.prototype

        Children.prototype = new tem()
        Children.prototype.constructor = Children
    }

    // 父类
    function Parent() {this.eyes = 'blue'; this.color=['red','yellow','black']}
    Parent.prototype.size = [1,2]
    Parent.prototype.getEyes = function getEyes() {
        console.log(this.eyes)
    }

    // 子类
    function Children() {Parent.call(this)}

    // 验证
    extend(Children, Parent)
    let chilren1 = new Children()
    let chilren2 = new Children()

    chilren1.getEyes() // blue

    // 构造函数上的this
    chilren1.color.push('esp')
    console.log('chilren2.color', chilren2.color) // color不存在

    // 原型上
    chilren1.size.push(3)
    console.log('chilren2.color', chilren2.size)  // [1, 2, 3]

 

posted on 2021-05-13 18:37  liu-mengyu  阅读(89)  评论(0)    收藏  举报