【JS】ES6-Class

如何理解JS中的Class?

在 ES6 规范中,引入了class的概念。使得 JS 开发者终于告别了,直接使用原型对象模仿面向对象中的类和类继承时代。

但是JS 中并没有一个真正的class原始类型,class仅仅只是对原型对象运用语法糖。所以,只有理解如何使用原型对象实现类和类继承,才能真正地用好class。

class实际上还是一个构造函数。

Class的使用与ES5有哪些不同?

    //es5
    // function Point(x,y){
    //     this.x = x;
    //     this.y = y;
    // }
    // Point.prototype.toString = function(){
    //     return this.x + ',' + this.y;
    // }
    // var p = new Point(100,200);

    //es6
    class Point{
        constructor(x,y){   //构造函数
            this.x = x;
            this.y = y;
        }
        toString(){
            return this.x + ',' + this.y;
        }
    }
    let p = new Point(100,200);
    console.log(p);

 

 可以看到是将toString方法写到了原型中,再调用。

Class的使用:

class中,带有static前缀的属于静态属性或静态方法,没有的属于实例方法。

    class Book{
        constructor(name,author,type,info){
            this.name = name;
            this.author = author;
            this.type = type;
            this.info = info;
        }

        static address = "新华书店";

        static showClassName(){
            console.log("小说");
        }

        sale(){
            console.log("打折促销");
        }
    }

    let sanguo = new Book("三国","罗贯中","小说","群雄争霸");
    console.log(sanguo);
    sanguo.sale();
    Book.showClassName();
    sanguo.showClassName();

 静态方法(静态属性)只能用构造函数或类名调用。

Class继承:

    //圆
    class Circle{
        constructor(ctx,x,y,z){
            this.ctx = ctx;
            this.x = x;
            this.y = y;
            this.r = r;
        }
        draw(){
            ctx.beginPath();
            ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
            ctx.closePath();
            ctx.stroke();
        }
    }
    
    //子类  彩色的圆
    class ColorfulCircle extends Circle{
        constructor(x,y,r,color){
            //super执行父级的构造函数constructor
            super(x,y,r); 
            //实现子类的属性   
            this.color = color;
        }
        draw(){
            ctx.beginPath();
            ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
            ctx.closePath();
            ctx.strokeStyle = this.color;
            ctx.stroke();
        }
    }

子类中出现与父类中同名的方法,会重写继承来的父类的方法,但是不影响父类的方法。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值