前端 JS面向对象 继承

目录

一、ES5通过prototype来继承

二、ES6 class实现


一、ES5通过prototype来继承

    const Person={
        eyes:2,
        head:1
    }
    function Woman(){

    }
    Woman.prototype=Person
    const lady=new Woman()
    console.log(lady)
    function Man(){

    }
    Man.prototype=Person
    const man=new Man()
    console.log(man)

打印:

不过,上面的写法还是有点问题,并没有制定原来的构造函数是谁,规范书写如下:

    const Person={
        eyes:2,
        head:1
    }
    function Woman(){

    }
    Woman.prototype={
        ...Person,
        //指回原来的构造函数
        constructor:Woman
    }
    const lady=new Woman()
    console.log(lady)
    function Man(){

    }
    Man.prototype=Person
    //指回原来的构造函数W
    Man.prototype.constructor=Man
    const man=new Man()
    console.log(man)

打印:

这里我不难看出,第一种写法也存在一种问题,两个类型继承同一各方法时,修改的原型对象是同一各个导致一些修改上的问题。

由此演进出不会影响修改的更优方案:通过构造函数来实现

    function Person(){
        this.eyes=2
        this.head=1
    }
    function Woman(){

    }
    Woman.prototype=new Person()
    Woman.prototype.constructor=Woman
    const lady=new Woman()
    console.log(lady)
    function Man(){

    }
    Man.prototype=new Person()
    //指回原来的构造函数W
    Man.prototype.constructor=Man
    const man=new Man()
    console.log(man)

打印:效果一样

二、ES6 class实现

直接通过class来标注,并且构造函数同一为constructor(), 允许静态方法,添加extends关键字进行继承。注意:类里面的所有代码将默认按严格模式进行执行。

    class Person{
        static alive=true
    
    
        //构造函数
        constructor() {
            this.eyes=2
            this.head=1
        }

        eat(){
            console.log("吃东西")
        }

        static isPerson(){
            //注意静态方法的this不再是对象而是类对象
            console.log("是个人")
        }
    }

    const p=new Person()
    p.eat()
    Person.isPerson()

    class Woman extends Person{
        constructor() {
            super()
            console.log("lady")
        }

    }
    const lady=new Woman()
    lady.eat()

打印:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值