手写一个简易的jQuery,考虑插件和扩展性

105 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    jquery 简易插件
    <p>111111</p>
    <p>222222</p>
    <p>333333</p>

</body>
<script>

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

// 演示效果
//    const $p = new jQuery('p')
//    $p.get(1)
//    $p.each((elem)=>console.log(elem.nodeName))
//    $p.on('click', ()=>alert('clicked'))

//扩展性1,插件,还是jquery
jQuery.prototype.dialog = function(info){
    alert(info)
}
//执行
// $p.dialog('abc')

//扩展性2:"造轮子",造的是我的,自己的
class myJQuery extends jQuery{
    constructor(selector){
        super(selector)
    }
    //扩展自己的方法
    addClass(aa){
        console.log('自己的插件',aa)
    }
} 

</script>
</html>