模仿jQuery实现一个API

如何模仿jQuery实现一个API?

jQuery是一个 JavaScript 库,核心理念是 - write less, do more。
其实jQuery就是一个函数,里面封装了很多方法,我们通过这些方法来获取节点(元素)并进行操作,大大方便了我们的编程。

  • 那么关于下面的代码,如何实现类似jQuery提供的api呢?
    1
    2
    3
    4
    5
    6
    window.jQuery = ???
    window.$ = jQuery

    var $div = $('div')
    $div.addClass(['red','blue']) // 可将所有 div 的 class 添加 red 和 blue 注意这里是数组的写法
    $div.setText('hi') // 可将所有 div 的 textContent 变为 hi
  1. 首先获取对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    window.jQuery = function(nodeOrSelector){
    let nodes = {} //初始化对象
    //判断用户想获取一个还是多个节点
    if(typeof nodeOrSelector === 'string'){ //多个节点
    let temp = document.querySelectorAll(nodeOrSelector) // 伪数组
    //遍历临时对象temp,将它的值放入nodes内,得到一个纯净的伪数组,原型链指向Object
    for(let i=0;i<temp.length;i++){
    nodes[i] = temp[i]
    }
    nodes.length = temp.length
    } else if(nodeOrSelector instanceof Node){ //一个节点
    nodes = {
    0: nodeOrSelector,
    length: 1
    }
    }
    return nodes //返回nodes
    }
  2. 添加addClass方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    nodes.addClass = function(classes){
    // 用户在addClass中输入的是数组所以用forEach
    classes.forEach((value) =>{
    //遍历nodes,为nodes内每一个元素节点添加class
    for(let i = 0 ; i<nodes.length; i++){
    nodes[i] .classList.add(value)
    }
    })
    }
  3. 添加setText方法

    1
    2
    3
    4
    5
    6
    nodes.setText = function(text){
    //遍历nodes,为nodes内每一个元素节点的textContent添加text
    for(let i=0;i<nodes.length;i++){
    nodes[i].textContent = text
    }
    }
  4. 完整代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    window.jQuery = function(nodeOrSelector){
    let nodes = {}
    if(typeof nodeOrSelector === 'string'){
    let temp = document.querySelectorAll(nodeOrSelector)
    for(let i=0;i<temp.length;i++){
    nodes[i] = temp[i]
    }
    nodes.length = temp.length
    } else if(nodeOrSelector instanceof Node){
    nodes = {
    0: nodeOrSelector,
    length: 1
    }
    }

    nodes.addClass = function(classes){
    classes.forEach((value) =>{
    for(let i = 0 ; i<nodes.length; i++){
    nodes[i] .classList.add(value)
    }
    })
    }

    nodes.setText = function(text){
    for(let i=0;i<nodes.length;i++){
    nodes[i].textContent = text
    }
    }

    return nodes
    }
    window.$ = jQuery

    var $div = $('div')
    $div.addClass(['red','blue']) // 可将所有 div 的 class 添加 red 和 blue
    $div.setText('hi') // 可将所有 div 的 textContent 变为 hi

完成,另外以上代码还使用到了JS的闭包。