js Class 與 普通構造函數有何區別

 

一、js構造函數

    let myCanvas = this.$refs.myCanvas
    var ctx = myCanvas.getContext('2d')

    function Circle (x, y, r, color) {
        this.x = x
        this.y = y
        this.r = r
        this.color = color
      }

      Circle.prototype.render = function () {
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true)
        ctx.fillStyle = this.color
        ctx.fill()
      }

      Circle.prototype.update = function () {
        this.x += 1
      }

      var yuan = new Circle(100, 100, 1, 'red')
      var timer
      clearInterval(timer)
      timer = setInterval(() => {
        // ctx.clearRect(0, 0, 800, 600)
        yuan.update()
        yuan.render()
        if (yuan.x === 800) {
          clearInterval(timer)
        }
      }, 15)

 

二、class基本語法

    let myCanvas = this.$refs.myCanvas
    var ctx = myCanvas.getContext('2d')
    class Circle {
        constructor (x, y, r, color) {
          this.x = x
          this.y = y
          this.r = r
          this.color = color
        }
        render () {
          ctx.beginPath()
          ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true)
          ctx.fillStyle = this.color
          ctx.fill()
        }
        update () {
          this.x += 1
        }
      }
      const yuan = new Circle(100, 100, 1, 'red')
      var timer
      clearInterval(timer)
      timer = setInterval(() => {
        // ctx.clearRect(0, 0, 800, 600)
        yuan.update()
        yuan.render()
        if (yuan.x === 800) {
          clearInterval(timer)
        }
      }, 15)

三、繼承

1、構造函數形式的繼承

 

//動物
function Animal(){
    this.eat = function (){
        console.log('Animal eat')
    }
}

//狗
function Dog() {
    this.bark = function (){
        console.log('Dog bark')
    }
}

Dog.prototype = new Animal()

var hashiqi = new Dog()
hashiqi.bark()
hashiqi.eat()

 

2、Class繼承

class Animal {
    constructor(name){
        this.name = name
    }
    eat(){
        alert(this.name + ' eat')
    }
}

class Dog extends Animal {
    constructor(name){
        super(name) //super就是被繼承的對象的constructer
    }
    say(){
        alert(this.name + ' say')
    }
}

const dog = new Dog('哈士奇')
dog.say()
dog.eat()

 四、總結


1、class在語法上更貼近面向對象的寫法。
2、class實現繼承更加易讀易理解。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章