使用class语法实现简易jquery,考虑插件和扩展性

class JQ {
  constructor (name) {
    const nodes = document.querySelectorAll(name)
    const len = nodes.length
    this.len = len
    for (let index = 0; index < len; index++) {
      this[index] = nodes[index]
    } 
  }
  get (index) {
    return this[index]
  }
  each (fn) {
    for (let index = 0; index < this.len; index++) {
      fn(this[index])
    }
  }
  on (type, fn) {
    this.each(ele => {
      ele.addEventListener(type, fn, false)
    })
  }
}

// 通过原型实现插件
JQ.prototype.myFun = function () {
  console.log('myFun')
}
// 通过extends实现扩展功能
class MyJQ extends JQ {
  constructor (props) {
    super(props)
  }
}

results matching ""

    No results matching ""