JQuery 的元素选择器的实现原理

jQuery源码的结构

(function( window, undefined) {
   
    var jQuery = (function() {
       // 构建jQuery对象
       var jQuery = function( selector, context ) {
           return new jQuery.fn.init( selector, context, rootjQuery );
       }
   
       // jQuery对象原型
       jQuery.fn = jQuery.prototype = {
           constructor: jQuery,
           init:  function ( selector, context, rootjQuery ) {
           }
       };
   
       // 合并内容到第一个参数中,后续大部分功能都通过该函数扩展
       // 通过jQuery.fn.extend扩展的函数,大部分都会调用通过jQuery.extend扩展的同名函数
       jQuery.extend = jQuery.fn.extend = **function**() {};
      
       // 在jQuery上扩展静态方法
       jQuery.extend({
           
       });
 
        // 到这里,jQuery对象构造完成,后边的代码都是对jQuery或jQuery对象的扩展
       return jQuery;
   
    })();
   
    window.jQuery = window.$ = jQuery;
})(window);

下面是模拟jQuery实现简单的获取元素内容

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>

<body>
    <div id="testText">
        测试文本
    </div>
</body>
<script>
    (function (window, undefined) {
        var rootjQuery = window.document;
        var jQuery = (function () {
            var jQuery = function (selector, context) {
                return new jQuery.fn.init(selector, context, rootjQuery);
            }

            jQuery.fn = jQuery.prototype = {
                construct: jQuery,
                init: function (selector, context, rootjQuery) {
                    var that = this;
                    that.ele = null;
                    that.value = '';
                    if (selector.charAt(0) === '#') {
                        console.log(selector);
                        that.ele = document.getElementById(selector.slice(1));
                    }
                    that.getValue = function () {
                        that.value = that.ele ? that.ele.innerHTML : 'No value';
                        return that;
                    };
                    that.showValue = function () {
                        return that.value;
                    };
                }
            };

            jQuery.fn.init.prototype = jQuery.fn;
            return jQuery;
        })();

        window.jQuery = window.$ = jQuery;
    })(window);


    //测试
    var testText = $('#testText').getValue().showValue(); //
    alert(testText);
</script>

</html>

结论

所以,JQuery 其实就是在一个匿名自调用函数内来实现把JQuery 作为 window 对象的方法,这样,当我们想使用 JQuery 的时候,就可以通过 window.JQuery() 或 window.$() 来使用,因为 window 对象的属性和方法都是全局的,所以也可以简写为 JQuery() 或 $()。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容