继承的几种方式

es5继承常用的继承

原型链继承

        function Father() {
            this.name = '父'
            this.age = [1, 2, 3, 4]
        }
        Father.prototype.getName = function () {
            return this.name
        }
        function Child() {
            this.child = '子'
        }
        Child.prototype = new Father()
        let child1 = new Child()
        let child2 = new Child()
        child1.age.push(5)
        console.log(child1.age, child2.age);//child1.age === child2.age
        //因为这两个实例使用同一个原型对象,所以共享同一块内存地址
        console.log(child1.getName()) // '父'

构造函数

        function Father() {
            this.name = '父'
            this.age = [1, 2, 3, 4]
        }
        Father.prototype.getName = function () {
            return this.name
        }
        function Child() {
            Father.apply(this)
            this.child = '子'
        }
        let child1 = new Child()
        let child2 = new Child()
        child1.age.push(5)
        console.log(child1.age, child2.age); //两个实例互不影响
        //相比第一种(原型链继承)做了优化,但也有弊端,只能继承父的实例属性和方法,继承不到父的原型属性和方法
        console.log(child1.getName());//会报错 拿不到

组合继承

        function Father() {
            this.name = '父'
            this.age = [1, 2, 3, 4]
        }
        Father.prototype.getName = function () {
            return this.name
        }
        function Child() {
            Father.apply(this)
            this.child = '子'
        }
        Child.prototype = new Father()
        //Child.prototype.constructor = Child
        let child1 = new Child()
        let child2 = new Child()
        child1.age.push(5)
        console.log(child1.age, child2.age);
        console.log(child1.getName());

es6使用class继承

class类

        class father {
            constructor(name,age){ //父的构造函数
                this.name = name //父的属性
                this.age = age //父的属性
                this.fn = ()=>{ //父的方法
                    console.log('父函数');
                }
            }
            say(){ //父的方法
                console.log(this.name);
            }
        }
        let f = new father('父','18') //父的实例化
        class child extends father{ //子继承父
            constructor(name,age){ //子的构造函数
                super(name,age) //子继承父的属性
                this.child = '子' //子自己的属性
            }
            cn(){
                console.log(this); //子自己的方法
            }
        }
        let child1 = new child(f.name,f.age) //子可以调用父的属性
        console.log(child1);  
        child1.fn() //子可以调用父的方法
        child1.say() //子可以调用父的方法
        //class构造函数里的方法和外面的方法是一样的,只是写法不一样

本章介绍继承属于自己的一个理解,加深一下基本印象,如有错误,还请指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值