描述:
JS面向对象——打印正方形、圆形
效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/*
*
* class
* constructor
* extends
* super();
* super.方法
* static 方法
*
*
* */
//类名
class Box{
// 构造函数
constructor(_parent,_wh,_color){
this.wh=_wh;
this.color=_color;
this.boxElem=this.createBox(_parent);
}
createBox(_parent){
if(this.boxElem)return;
let div=document.createElement("div");
div.style.width=div.style.height=this.wh+"px";
div.style.backgroundColor=this.color;
div.style.position="absolute";
_parent.appendChild(div);
return div;
}
move(x,y){
this.boxElem.style.left=x+"px";
this.boxElem.style.top=y+"px";
}
}
class Ball extends Box{
constructor(_parent,_wh,_color){
// super()就是执行继承的父类的构造函数
super(_parent,_wh,_color)
}
createBox(_parent){//相当于重写 加了相应的功能 圆的功能
let elem=super.createBox(_parent);
elem.style.borderRadius=this.wh/2+"px";
return elem;
}
// 类的静态方法
static getRandomColor(){
let col="#";
for(let i=0;i<6;i++){
col+=Math.floor(Math.random()*16);
}
return col;
}
}
let box1=new Box(document.body,50,"red");
box1.move(200,200);
let ball1=new Ball(document.body,50);
ball1.move(500,500);
Ball.getRandomColor();
</script>
</body>
</html>