面试题:手写jquery要求考虑插件扩展性

class Jquery {
  constructor(selector) {
    const result = document.querySelectorAll(selector)
    const length = result.length
    for(let i = 0; i < length; i++) {
      this[i] = result[i]
    }
    this.length = length
  }
  get(index) {
    return this[index]
  }
  each(fn) {
    for(let i = 0;i < this.length; i++) {
      const elem = this[i]
      fn(elem)
    }
  }
  on(type, fn) {
    return this.each(elem => {
      elem.addEventListener(type, fn, false)
    })
  }
}

// 插件
Jquery.prototype.dialog = function (info) {
  alert(info)
}

// 造轮子
class myJquery extends Jquery {
  constructor(selector) {
    super(selector)
  }
  addClass(className) {

  }
}

posted on 2021-06-09 13:15  是庸  阅读(34)  评论(0编辑  收藏  举报