ECMAScript6写class

71 阅读1分钟
  1. 子类可以通过extend关键字来继承父类的属性和方法;通过super来给父类中的属性赋值;
  2. static方法使用类来调用,普通函数使用实例调用;
  3. setter/getter函数名一样,一个用来改写一个用来获取;
  • 完成一个简单的“废话生成器”
<html>
  <input type="text"/>
  <button class="button_1">一级废话</button>
  <button class="button_2">二级废话</button>
</html>
<script>
    const input = document.querySelector('input')
    const button_1 = document.querySelector('.button_1')
    const button_2 = document.querySelector('.button_2')
    const p = document.querySelector('p')

    class Bullshit {
      static tips (){
        return "tips"
      }
      static tips_() {
        console.log(this.tips())
      }
      set extra (value) {
        this.value = value
        p.innerHTML = p.innerHTML + this.value
      }
      get extra () {
        return '111'
      }
      constructor(text, color) {
        this.text = text
        this.color = color
      }
      show () {
        p.innerHTML = this.text + input.value
        p.style.color = this.color
      }
    }
    class Son_bullshit extends Bullshit {
      constructor(text, color, fontsize) {
        super(text, color)
        this.fontsize = fontsize
      }
      show() {
        p.innerHTML = this.text + p.innerHTML
        p.style.color = this.color
        p.style.fontsize = this.fontsize
      }
    }
    button_1.addEventListener('click', () => {
      const bullshit = new Bullshit('我直接', '#000')
      bullshit.show()
    })
    button_2.addEventListener('click', () => {
      const son_bullshit = new Son_bullshit('我知道', '#000')
      son_bullshit.show()
    })
    p.addEventListener('click', () => {
      Bullshit.tips_()
    })

</script>