JavaScript - 继承

上一节原型链可以实现简单的继承,那原型链继承存在什么问题,以及哪种方式能够完美的实现继承

  1. 原型链继承:将父类的实例作为子类的原型
        // 由于所有Child实例原型都指向同一个Parent实例, 因此对某个Child实例的父类引用类型变量修改会影响所有的Child实例
        // 在创建子类实例时无法向父类构造传参, 即没有实现super()的功能
        Grand.prototype.lastName = "cc"
        function Grand() { }
        let grand = new Grand()

        Father.prototype = grand
        function Father() {
            this.name = "hh"
        }
        let father = new Father()

        Son.prototype = father
        function Son() {}
        let son = new Son()
        
        //想继承grand的lastName 但是father的name也会继承
        //son.name = "hh"
        //son.lastName = "cc"

特点:过多继承没用的属性;无法实现多继承;无法向父类构造函数传参
2. 借用构造函数:使用父类的构造函数来增强子类实例

        //不能继承借用构造函数的原型;每次构造函数都要多走一个函数,运行时没有省,
        function Person(name, age, sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        function Student(name, age, sex, grade) {
            Person.call(this, name, age, sex)
            this.grade = grade;
        }
        var student = new Student('cc', 18, '女', 100)

特点:可以实现多继承;只能继承父类的实例属性和方法,不能继承原型属性和方法;无法实现函数服用
3. 共享原型:公用同一个原型对象

// 不能有自己独立的属性
Father.prototype.name = '车车'
function Father() {}
function Son() {}

Son.prototype = Father.prototype
let father = new Father()
let son = new Son()
Son.prototype.sex = '女'  //father也会有sex

console.log(father.sex) 

特点:不能随便改动自己的原型不能拥有自己独特属性,因为改变自己会影响他人
4. 圣杯模式:就是添加一个中间层

Father.prototype.name = '车车'
function Father() {}
function Son() {}

function Fn() {}
Fn.prototype = Father.prototype;
Son.prototype = new Fn()
// 进行归位
Son.prototype.constructor = Son

let father = new Father()
let son = new Son()
Son.prototype.sex = '女'

console.log(son.name)
console.log(father.sex) //undefined
console.log(Son.prototype.constructor)  //Father  指向紊乱 应该指向Son 所以上面进行归位

5.ES6中的继承

class Father {
    constructor(name) {
        this.name = name
    }
    my() {
        console.log(this.name)
    }
}

class Son extends Father {
    constructor(name, age) {
        super(name)
        // super 类似于 Father().call(this,name)
        this.age = age
    }
}
var father = new Father('bb')
var son = new Son('cc', 18)
console.log(son)     //Son { name: 'cc', age: 18 }
console.log(father)  //Father { name: 'bb' } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值