手写简易的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;
    this.selector = selector;
    // 类似于数组
  }
  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);
    })
  }
  // 扩展很多
}

// 
// const p = new jQuery('p');
// p.get(1);
// p.each((elem)=>console.log(elem.nodeName))
// p.on('click', ()=>alert('clicked'))

// 插件
jQuery.prototype.dialog = function (info) {
  alert(info)
}
const p = new jQuery('p')
p.dialog('avd');

// 造*
class myJQuery extends jQuery{
  constructor(selector){
    super(selector)
  }
  // 扩展自己的方法
  addClass(className){}
  styleData(data){}
}

 

上一篇:顺序表的插入删除算法移动元素次数分析


下一篇:顺序存储线性表