A front-end knowledge every day 13 - handwritten jquery

Summarize

Use anonymous self-executing functions to mount public methods on prototypes and encapsulate for loops

the code

// 匿名自执行函数
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)
  }
})()

Guess you like

Origin blog.csdn.net/qq_33591873/article/details/128358077