像 jQuery 一樣封裝 API

一、前言

jQuery 作為 JavaScript 函數(shù)庫,是一種特定種類的API。它的功能強(qiáng)大而豐富,幫助解放了DOM API。即使在如今框架盛行的時(shí)代,仍然值得我們學(xué)習(xí)。
在正式學(xué)習(xí)使用 jQuery API 之前,讓我們仿造其形式試著自己封裝兩個(gè) API 。

二、實(shí)現(xiàn)目標(biāo)

封裝 addClass、setText 兩個(gè)函數(shù),實(shí)現(xiàn)
① 為元素批量添加類
② 設(shè)置元素中的文本內(nèi)容

var $div = $('div')
$div.addClass('red') // 可將所有 div 的 class 添加一個(gè) red
$div.setText('hi') // 可將所有 div 的 textContent 變?yōu)?hi

三、步驟

1. 封裝三個(gè)好用的函數(shù) getSiblings、addClass、setText。
// 匹配 節(jié)點(diǎn)node
function getSiblings(node) {
    var allChildren = node.parentNode.children
    var arr = { length: 0 }
    for (let i in allChildren) {
        if (allChildren[i] != node) {
            arr[arr.length] = allChildren[i]
            arr.length += 1
        }
    }
    return arr
}

function addClass(node, thoseClass) {
    // 參數(shù) thoseClass 支持字符串和數(shù)組
    if(typeof thoseClass === 'string') {
        node.classList.add(thoseClass)
    }else if(Array.isArray(thoseClass)) {
        thoseClass.forEach( value => node.classList.add(value) ) 
    }
}

function setText(node, content) {
    node.textContent = content
}

console.log( getSiblings(node) )
addClass(node, ['red', 'big', 'center'])
setText(node, 'hi')

使用命名空間,如庫YUI

xinDom = { 
    addClass: function(node, thoseClass) {
        // 參數(shù) thoseClass 支持字符串和數(shù)組
        if(typeof thoseClass === 'string') {
            node.classList.add(thoseClass)
        }else if(Array.isArray(thoseClass)) {
            thoseClass.forEach( value => node.classList.add(value) ) 
        }
    },
    setText: function (node, content) {
        node.textContent = content
    }
}
xinDom.addClass(node, ['red', 'big', 'center'])
xinDom.setText(node, 'hi')
2. 節(jié)點(diǎn)node 放到前面調(diào)用
1)擴(kuò)展Node接口。將函數(shù)添加到 節(jié)點(diǎn)原型(Node.prototype)中,則節(jié)點(diǎn)node可直接調(diào)用
Node.prototype.addClass = function(thoseClass) {
    // 使用 this 得到 節(jié)點(diǎn)node
     if(typeof thoseClass === 'string') {
        this.classList.add(thoseClass)
    }else if(Array.isArray(thoseClass)) {                         
        thoseClass.forEach( value => this.classList.add(value) )        
    }
}

Node.prototype.setText = function(content) {
    this.textContent = content
}

node.addClass.call(node, 'red') // 或 node.addClass('red')
node.setText.call(node, 'hi')   // 或 node.setText('hi')
  • 這種方式可能因重名導(dǎo)致互相覆蓋,從而擾亂了已有的原型。因此使用第 2)種方法。
2)使用新的接口。創(chuàng)建一個(gè)構(gòu)造函數(shù) jQuery,返回封裝了自有API的對(duì)象
  • 不止接受節(jié)點(diǎn)
// 匹配 節(jié)點(diǎn)node 或 選擇器
window.jQuery = function(nodeOrSelector) {

    var nodes = {}
    if(typeof nodeOrSelector === 'string') {
        
        var tmp = document.querySelectorAll(nodeOrSelector)
        nodes.length = tmp.length
        for(var i=0; i<tmp.length; i++) {
            nodes[i] = tmp[i]
        }

    }else if(nodeOrSelector instanceof Node) {
        nodes = {
            0: nodeOrSelector,
            length: 1
        }
    }

    return {
        elements: nodes,
        addClass: function(thoseClass) {

            if(typeof thoseClass === 'string') {
                for(var i=0; i<nodes.length; i++) {
                    nodes[i].classList.add(thoseClass)
                }
            }else if(Array.isArray(thoseClass)) {
                for(var i=0; i<nodes.length; i++) {                            
                    thoseClass.forEach( value => nodes[i].classList.add(value) )
                }
            }

        },
        setText: function(content) {                    

            for(var i=0; i<nodes.length; i++) {
                nodes[i].textContent = content
            }
            
        }
    }
}

jQuery('div').setText('hi')
  • jQuery 這個(gè)函數(shù)中使用到了閉包。
3. 使用縮寫,$ 指代 jQuery
window.$ = jQuery

var $div = $('div')
$div.addClass('red') // 可將所有 div 的 class 添加一個(gè) red
$div.setText('hi')
  • 通過上述仿造 jQuery 封裝 API 的過程,可窺見 jQuery 的本質(zhì),是一個(gè)構(gòu)造函數(shù)接收一個(gè)節(jié)點(diǎn)或符合某要求的字符串(如選擇器),然后返回給我們一個(gè)含有豐富 API 的對(duì)象,通過調(diào)用 API 來操作相應(yīng)的 DOM 對(duì)象。
    【不成文的規(guī)定】jQuery 構(gòu)造出的對(duì)象,其引用變量會(huì)以 $ 開頭,與普通變量區(qū)分開。

四、jQuery 只是這樣?

窺探了 jQuery 本質(zhì),它的強(qiáng)大并不僅限如此,jQuery 函數(shù)庫的優(yōu)點(diǎn)概括:

  1. 兼容性方面做得很棒。
  2. 不止提供了便捷的 DOM 操作,還有動(dòng)畫、Ajax等豐富的功能。
  3. jQuery 不僅使用了 prototype,還使用了 new(還未學(xué)到)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、樣式篇 第1章 初識(shí)jQuery (1)環(huán)境搭建 進(jìn)入官方網(wǎng)站獲取最新的版本 http://jquery.co...
    凜0_0閱讀 3,670評(píng)論 0 44
  • jQuery jQuery是JavaScript世界中使用最廣泛的一個(gè)庫。 jQuery這么流行,肯定是因?yàn)樗鉀Q...
    星騰_范特西閱讀 2,195評(píng)論 0 27
  • 概要 64學(xué)時(shí) 3.5學(xué)分 章節(jié)安排 電子商務(wù)網(wǎng)站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,849評(píng)論 0 3
  • 第一章 jQuery簡介 1-1 jQuery簡介 1.簡介 2.優(yōu)勢 3.特性與工具方法 1-2 環(huán)境搭建 進(jìn)入...
    mo默22閱讀 1,774評(píng)論 0 11
  • 美好的一天開始啦! 揮揮小手我們來給每位小朋友問好吧 “早上好 ,早上好,早上好” 今天我們班來了一位新同學(xué)——星...
    apple_Mia閱讀 415評(píng)論 0 0

友情鏈接更多精彩內(nèi)容