1. 程式人生 > >ES6——Class的繼承

ES6——Class的繼承

height cancel xtend http offset quest tran doctype current

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的繼承