用 JS 封装一个库的基本思路

282 阅读1分钟

今天我尝试用 JS 来实现 jQuery 中最简单的 API:addClass,一共有三种写法:

第一种是使用闭包,代码如下:

function jQuery(选择器) {
  const 标签伪数组 = document.querySelectorAll(选择器)
  const 标签数组 = Array.from(标签伪数组)
  const api = {
    addClass(className) {
      标签数组.forEach((标签) => {
        标签.classList.add(className)
      })
    }
  return api
}

第二种是使用构造函数(或者说原型),代码如下:

function jQuery(选择器) {
  const 标签伪数组 = document.querySelectorAll(选择器);
  this.标签数组 = Array.from(标签伪数组);
}
jQuery.prototype = {
  constructor: jQuery,
  addClass(className) {
    this.标签数组.forEach((标签) => {
      标签.classList.add(className);
    });
  }
};

const $ = jQuery;
// 用法
const button = document.getElementById("btn");
button.onclick = function () {
  new $(".red").addClass("green");
};

第三种是使用类,代码如下:

class jQuery {
  constructor(选择器){
    this.所有元素的伪数组 = document.querySelectorAll(选择器)
    this.所有元素 = Array.from(this.所有元素的伪数组)
  }
  addClass(className) {
    const { 所有元素 } = this
    for (let i = 0; i < 所有元素.length; i++) {
      所有元素[i].classList.add(className)
    }
  }
}
const $ = jQuery
// 用法
const button = document.getElementById('btn')
button.onclick = () => {
  new $('.red').addClass('green')
}