es6规范的class使用方法

22 篇文章 0 订阅

对于科班出身的程序员来说,class是啥玩意就不必哆嗦了,直接讲吧
在之前规范的写法是这样子的

//es5的常规用法
    //手机
    function phone(brand,price){
        this.brand=brand;
        this.price=price;
    }

    //添加方法
    //prototype是函数对象上面预设的对象属性
    phone.prototype.call=function(){
        console.log("我可以打电话");
    }
    //实例化对象
    let HUAWEI=new phone('华为',69999);
    HUAWEI.call();
    console.log(HUAWEI);

在这里插入图片描述
到了es6,我们可以运用class来处理了,一般我们在java怎么面向对象编程,这里就可以怎么面向对象编程。

//es6语法
    class Phone{
        
        //构造方法,固定
        constructor(brand,price){
            this.brand=brand;
            this.price=price;
        }
        static name='手机';//静态属性,属于类,不属于对象

        //方法必须使用该语法,不能使用es5的对象形式.
        call(){
            console.log("店电话");
        }
    }
    let XIAOMI=new Phone("小米",1999);

    //输出静态对象,啥事静态对象不知道的自己去查
    console.log(XIAOMI);
    console.log(XIAOMI.name);//undifine
    console.log(Phone.name);//手机

在这里插入图片描述
那其他面向对象编程的内容有没有呢,当然有
比如继承
这是父类

class Phone{
        //构造方法
        constructor(brand,price){
            this.brand=brand;
            this.price=price;
        }

        //父类的成员函数
        call(){
            console.log("dianhua");
        }
        chongxie(){
            console.log("父类还没从写的时候");
        }
    }

继承的子类

class SmartPhone extends Phone{
        //子类构建方法
        constructor(brand,price,color,size){
            super(brand,price);
            this.color=color;
            this.size=size;
        }
        chongxie(){
            console.log("子类重写函数");
            // super.call();
        }
        photo(){
            console.log("photo");
        }
        playgame(){
            console.log("playgame");
        }
        get aa(){
            console.log("aa");
        }
    }

这时候输出一下

const xiaomi=new SmartPhone('小米',5555,'black',40);
    console.log("父类的东西"+xiaomi.brand);
    console.log("子类的东西"+xiaomi.color);
    xiaomi.chongxie();

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值