jQuery.fn.init

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Trifling_/article/details/69668774

  var rootjQuery,
        rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
        init = jQuery.fn.init = function( selector, context, root ) {
            var match, elem;

            // 处理 $(""), $(null), $(undefined), $(false),就直接返回当前this
            if ( !selector ) {
                return this;
            }

            root = root || rootjQuery;

            // 处理字符串eg:$("#id")...
            if ( typeof selector === "string" ) {
                // 这里提前部分特征代码说明,查看源码其它类似,
                //$("#id") $(".class") .... 通过正则表达判断string类型,分类处理
                /*  eg: HANDLE: $(#id)
                elem = document.getElementById( match[ 2 ] );
                if ( elem ) {
                    this[ 0 ] = elem;
                    this.length = 1;
                }
                return this;*/
                // 关键是这里的返回值this,this指向调用当前方法的对象即 new jQuery.fn.init()
                // this[ 0 ] = elem; 表示添加到当前new jQuery.fn.init()
            }
            // 处理当前节点eg $(document)...
            else if ( selector.nodeType ) {
                this[ 0 ] = selector;
                this.length = 1;
                return this;
            }
            // $(function(){}) 当document载入完成后执行,
            else if ( jQuery.isFunction( selector ) ) {
                return root.ready !== undefined ?
                    root.ready( selector ) :

                    selector( jQuery );
            }
            return jQuery.makeArray( selector, this );
        }; 
		init.prototype = jQuery.fn;

注意: 这个方法中的this, 当new jQuery.fn.init()的时候this指向new jQuery.fn.init()即当前调用者也是$(“#id”),如果不是new 的这个方法,则它指向jQuery.fn

PS: 最后返回的值是 jQuery.fn.init ,并指向jquery.fn , 上张图一切都明白啦


猜你喜欢

转载自blog.csdn.net/Trifling_/article/details/69668774