JavaScript 练手小技巧:ES6利用 class 定义类和对象

今天看资料,看到了一个高手写的代码,甚为佩服,学了过来,再次理解了下 JavaScript 中 class 定义类和对象。

该代码使用 class 定义了一个圆圈。利用 canvas 绘制一个圆。

HTML:

<canvas id="cvs" width="400" height="400"></canvas>

JavaScript: 

class Circle{
    constructor(ops) {
        this.x = 0 ;
        this.y = 0 ;
        this.r = 100 ;
        this.strokeStyle = "#f00";
        this.fillStyle = "#f00";
        Object.assign(this, ops);
        return this;
    }
    createPath(ctx){
        let {strokeStyle, fillStyle, r} = this ;
        ctx.strokeStyle = strokeStyle;
        ctx.fillStyle = fillStyle ;
        ctx.beginPath();
        ctx.arc(0, 0 ,r,  0 , Math.PI*2, true );
        return this;
    }
    render(ctx){
        let {x, y} = this ;
        ctx.save();
        ctx.translate( x , y );
        this.createPath(ctx);
        ctx.stroke();
        ctx.fill();
        ctx.restore();
        return this;
    }
}
let cvs = document.getElementById("cvs");
let ctx = cvs.getContext("2d");

let y1 = new Circle({
        x: 100,
        y: 200,
        r: Math.random()*20
})
y1.render(ctx);

这里面经典的地方在于:

1. 利用了 ES6 对象解构的方式,获取对象的属性值,并赋给同名变量。

关于结构,可以看我的这篇文章

2.把 canvas 的路径绘制和图像绘制,分成了两个方法进行,功能不会混在一起,代码更清晰。

3.把 类的构造函数的参数,写出了对象的方式,且给各个属性给予了默认值,利用 ES6 新增的对象 Object.assign 方法覆盖默认值。

总结:

果然还是要多看点东西,多跟高手学习。

记录一下。感谢今日,又获得了新知识。

猜你喜欢

转载自blog.csdn.net/weixin_42703239/article/details/113731016