前端面试题整理——手写简易jquery

    class jQuery {
        constructor(selector) {
            const result = document.querySelectorAll(selector)
            console.log(result)
            const length = result.length
            for (let i = 0; i < length; i++) {
                this[i] = result[i]
            }
            this.length = length
        }
        get(index) {
            return this[index]
        }
        each(fn) {
            for (let i = 0; i < this.length; i++) {
                const ele = this[i]
                fn(ele)
            }
        }
        on(type, fn) {
            return this.each(ele => {
                ele.addEventListener(type, fn, false)
            })
        }
    }

    //考虑扩展性
    //插件
    jQuery.prototype.dialog = function (info){
        alert(info)
    }
    //复写机制
    class MyJQuery extends jQuery{
        constructor(selector){
            super(selector)
        }
        addClass(className){}
        style(data){}
    }


    //使用
    const jq = new jQuery('p')
    console.log(jq.get(0))
    jq.each(function(el){
        console.log(el)
    })
    jq.on('click',function(el){
        console.log(el)
    })

考点:

  • 原型和原型链的理解
  • dom操作
放弃安逸,持续努力——成长
原文地址:https://www.cnblogs.com/MarsPGY/p/13461950.html