如何使用Javascript代理重写此代码?

时间:2020-07-30 16:32:34

标签: javascript

我刚刚了解了JavaScript Proxies。我正在阅读一个试图重新创建jQuery的教程。我了解整个代码。最后,讲师-编码花园的CJ说我们可以使用代理。 (this is the youtube tutoriall

我得到了MDN文档,但我不知道它将如何发挥作用。这是代码jsbin

const makeNiceCollection = (collection) => {
    collection.each = (callback) => { // 27:05
        collection.forEach((element, i) =>{ // each === forEach
             // then "this" = window. So bind it to element instead
            const boundFn = callback.bind(element)
            boundFn(i, element) // then run the callback
        })
    }
    collection.on = (eventName, handler) => {
     collection.forEach(element => {
         element.addEventListener(eventName, handler)

     })
    }
    collection.css = (...cssArgs) => {
         if(typeof cssArgs[0] === 'string'){
             const [property, value] = cssArgs;
             collection.forEach((element) => {
                 element.style[property] = value
             })
         } else if(typeof cssArgs[0] === 'object'){
             const cssProps = Object.entries(cssArgs[0]);
             collection.forEach(element => {
                 cssProps.forEach(([property, value]) => {
                         element.style[property] = value
                     
                 })
             })
             
         }

    }
}
const $ = (...args) => {
 
    if(typeof args[0] === 'function') {
        const readyFn = args[0]
        document.addEventListener('DOMContentLoaded', readyFn)
    } else if (typeof args[0] === 'string'){
        const selector = args[0]
        // look up querySelectorAll and you'll find it's a node list
       const collection = document.querySelectorAll(selector)
       makeNiceCollection(collection)
      return collection  

    } else if (args[0] instanceof HTMLElement){
        // or (typeof args[0] === 'object' && args[0].constructor.name.startsWith('HTML'))
        // 35:07
        const collection = [args[0]]
        makeNiceCollection(collection)
        return collection
    }
 
}

您能给我一些有关如何使用代理的指示吗

0 个答案:

没有答案