美文网首页
JavaScript - 封装简单版 jQuery

JavaScript - 封装简单版 jQuery

作者: Hyso | 来源:发表于2019-04-13 14:45 被阅读0次
    • 模块化
    (function(){
        ......            
    })()
    
    • 声明一个 jQuery 函数
    (function(){
        // 声明一个 jQuery函数
        function jQuery(){
                    
        }
    
        // 给 window 对象添加一个 jQuery 函数
        window.$ = window.jQuery = jQuery;
    })()
    
    • 实现功能:$("div").css("color", "red")
    (function() {
        function jQuery(selector) {
            return new jQuery.prototype.init(selector);
        }
    
        window.$ = window.jQuery = jQuery;
    
        jQuery.prototype = {
            constructor:jQuery,
            init:function(selector) {
                var elements = document.querySelectorAll(selector);
                    
                for (var i=0; i<elements.length; i++) {
                    this[i] = elements[i];
                }
    
                this.length = elements.length;
            }
        }
    
        jQuery.prototype.init.prototype = {
            constructor:jQuery.prototype.init,
            css:function(name, value) {
                for (var i=0; i<this.length; i++) {
                    this[i].style[name] = value;
                }
            }
        }
    })()
    
    
    • 测试
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div>1</div>
        <div>2</div>
        <div>3</div>
    
        <script>
            (function() {
                function jQuery(selector) {
                    return new jQuery.prototype.init(selector);
                }
    
                window.$ = window.jQuery = jQuery;
    
                jQuery.prototype = {
                    constructor:jQuery,
                    init:function(selector) {
                        var elements = document.querySelectorAll(selector);
                    
                        for (var i=0; i<elements.length; i++) {
                            this[i] = elements[i];
                        }
    
                        this.length = elements.length;
                    }
                }
    
                jQuery.prototype.init.prototype = {
                    constructor:jQuery.prototype.init,
                    css:function(name, value) {
                        for (var i=0; i<this.length; i++) {
                            this[i].style[name] = value;
                        }
                    }
                }
            })()
    
            $("div").css('color', 'red');
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:JavaScript - 封装简单版 jQuery

          本文链接:https://www.haomeiwen.com/subject/kbrlwqtx.html