每天一个前端小知识13——手写jquery

总结

使用匿名自执行函数,将公共方法挂载在原型上,封装for循环

代码

// 匿名自执行函数
let $ = jQuery = (function (window) {
    
    
  let jquery = function (node) {
    
    
    this.nodes = document.querySelectorAll(node)
  }
  // 将公共方法挂载在原型上
  jquery.prototype = {
    
    
    // 封装for循环
    each: function (callback) {
    
    
      for (let i = 0; i < this.nodes.length; i++) {
    
    
        callback.call(this, i, this.nodes[i])
      }
    },
    // 添加class
    addClass: function (classes) {
    
    
      let className = classes.split('')
      className.forEach(value => {
    
    
        this.each(function (_, obj) {
    
    
          obj.classList.add(val)
        })
      })
    },
    // 修改text
    setText: function (text) {
    
    
      this.each(function (_, obj) {
    
    
        obj.textContent = text
      })
    }
  }

  return function (node) {
    
    
    return new jquery(node)
  }
})()

猜你喜欢

转载自blog.csdn.net/qq_33591873/article/details/128358077