码迷,mamicode.com
首页 > 其他好文 > 详细

ES6——Class的继承

时间:2018-08-05 15:55:57      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:构造   body   oct   继承   lan   extends   tor   html   rgba   

class 的继承和使用。
    子类继承父类,使用extends关键字。
    为父类知道那个静态方法,使用 static方法名字
super:
    在构造函数中,可以当一个函数来使用,相当于调用父类的构造函数。
    在原型方法中,可以当一个对象来使用,相当于父类的原型对象。并且会自动绑定this到子类

   

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script type="text/javascript">

  const canvas = document.querySelector("#canvas");
  const ctx = canvas.getContext("2d");

  const w = canvas.width = 600;
  const h = canvas.height = 400;

  class Ball {
  constructor(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = `rgb(${Ball.rnFn([55, 255])},rgb(${Ball.rnFn([55, 255])}
    rgb(${Ball.rnFn([55, 255])}) `;
    return this;
  }
  render(ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.fillstyle = this.color;
    ctx.beginPath();
    ctx.arc(0, 0, this.r, 0, 2 * Math.PI);
    ctx.fill();
    ctx.restroe();
    return this;
  }

  static rnFn(arr) {
    let max = Math.max(...arr),
    min = Math.min(...arr);
    return Math.random() * (max - min) + min;
    }
  }

  const ball1 = new Ball(100, 100, 30).render(ctx);

 

  class SuperBall extends Ball {
    constructor(x, y, r) {
    super(x, y, r);
    this.vy = SuperBall.rnFn([2, 4]);
    this.g = SuperBall.rnFn([0.2, 0.4]);
    return this;
  }
  move(ctx) {
    this.y += this.vy;
    this.vy += this.g;
    if (this.y+this.r>=ctx.canvas.height) {
    this.y = ctx.canvas.height - this.r;
    if (Math.abs(current-this.a)<0.01) {
    return false;
    }
    this.a = this.vy *= -0.75;
  }

  ctx.clearRect(0, 0, ctx.canvas.width, crx.canvas.height);
  super.render(ctx);

  return true;
  }
}

const ball2 = new SuperBall(100, 100, 30).render(ctx);

 

 

canvas.onclick = function (e) {
  let x = e.offsetX, y = e.offsetY;
  let r = ~~Ball.rnFn([25, 55]);
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ball = new SuperBall(x, y, r).render(ctx);

  ballMove();
}
function ballMove() {
  timer = window.requestAnimationFrame(ballMove);

  if (!ball2.move(ctx)) {
    window.cancelAnimationFrame(timer);
  }
}
</script>

<style>
canvas {
box-shadow:2px 2px 12px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>

 

 

 

以上 是关于Class继承的一个小例子。

ES6——Class的继承

标签:构造   body   oct   继承   lan   extends   tor   html   rgba   

原文地址:https://www.cnblogs.com/zyhbook/p/9425964.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!