您当前的位置: 首页 >  jquery

wespten

暂无认证

  • 0浏览

    0关注

    899博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

深入学习jquery源码之jQuery的构造函数与实例化

wespten 发布时间:2018-12-26 16:24:59 ,浏览量:0

深入学习jquery源码之jQuery的构造函数与实例化

创建jQuery对象的整个流程如下:

1、调用$()方法;

2、调用jQuery.prototype.init()构造函数;

3、根据选择器不同返回不同的jQuery对象;

4、不同jQuery对象中公用的方法写在jQuery.prototype中;

5、将jQuery.prototype传递给jQuery.prototype.init.prototype,这样新创建的对象才可以访问公用方法;

 

创建jquery对象的四个步骤

第一步:创建jquery构造函数,并且实例化jQuery.fn.init(jquery的构造函数)。因为实例化的不是jQuery对象所以这上面不会挂载jQuery的方法,同时通过原型链也访问不到,jQuery使用了无new构造:将init()构造函数的定义放在了jQuery.prototype里面

jQuery = function (selector, context) {
            // The jQuery object is actually just the init constructor 'enhanced'
            // Need init if jQuery is called (just allow error to be thrown if not included)
            return new jQuery.fn.init(selector, context);
}

 

在jQuery中,$是jQuery的别名,执行“$()”就是执行“jQuery()”,执行“$()”返回的是一个jQuery对象

    var
        // Map over jQuery in case of overwrite
        _jQuery = window.jQuery,

        // Map over the $ in case of overwrite
        _$ = window.$;

    jQuery.noConflict = function (deep) {
        if (window.$ === jQuery) {
            window.$ = _$;
        }

        if (deep && window.jQuery === jQuery) {
            window.jQuery = _jQuery;
        }

        return jQuery;
    };

    // Expose jQuery and $ identifiers, even in
    // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
    // and CommonJS for browser emulators (#13566)
    if (typeof noGlobal === strundefined) {
        window.jQuery = window.$ = jQuery;
    }
    return jQuery;

 

第二步:此方法则是用来扩展jQuery的实例方法,也就是说jQuery类的实例对象可以调用此函数

   $.fn.extend({

   theAlert:function(){

      alert("自定义的函数");

    }

  })

  $("thediv").theAlert()

jQuery.fn指向jQuery.prototype,jQuery.fn执行jQuery的原型对象。我们可以通过实例化的静态方法也就是我们的工具方法挂载在jQuery上,也可以获得jQuery.prototype上的属性。这样我们调用的时候不需要去实例化,而是可以直接去调用,将对象的方法挂载到jQuery.prototype上,我们系需要实例化之后才能够使用,针对的this的操作。

    jQuery.fn = jQuery.prototype = {
        // The current version of jQuery being used
        jquery: version,

        constructor: jQuery,

        // Start with an empty selector
        selector: "",

        // The default length of a jQuery object is 0
        length: 0,

        toArray: function () {
            return slice.call(this);
        },

        // Get the Nth element in the matched element set OR
        // Get the whole matched element set as a clean array
        get: function (num) {
            return num != null ?

                // Return just the one element from the set
                (num < 0 ? this[num + this.length] : this[num]) :

                // Return all the elements in a clean array
                slice.call(this);
        },

        // Take an array of elements and push it onto the stack
        // (returning the new matched element set)
        pushStack: function (elems) {

            // Build a new jQuery matched element set
            var ret = jQuery.merge(this.constructor(), elems);

            // Add the old object onto the stack (as a reference)
            ret.prevObject = this;
            ret.context = this.context;

            // Return the newly-formed element set
            return ret;
        },

        // Execute a callback for every element in the matched set.
        // (You can seed the arguments with an array of args, but this is
        // only used internally.)
        each: function (callback, args) {
            return jQuery.each(this, callback, args);
        },

        map: function (callback) {
            return this.pushStack(jQuery.map(this, function (elem, i) {
                return callback.call(elem, i, elem);
            }));
        },

        slice: function () {
            return this.pushStack(slice.apply(this, arguments));
        },

        first: function () {
            return this.eq(0);
        },

        last: function () {
            return this.eq(-1);
        },

        eq: function (i) {
            var len = this.length,
                j = +i + (i < 0 ? len : 0);
            return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
        },

        end: function () {
            return this.prevObject || this.constructor(null);
        },

        // For internal use only.
        // Behaves like an Array's method, not like a jQuery method.
        push: push,
        sort: deletedIds.sort,
        splice: deletedIds.splice
    };

 

第三步:jQuery.fn.extend(object)为jQuery对象添加方法,此方法是用来扩展jQuery类,它所方法是全局性,直接用jQuery类即可引用

$.extend({minValue:function(a,b){return a= 3) {
                    // Assume that strings that start and end with  are HTML and skip the regex check
                    match = [null, selector, null];

                } else {
                    match = rquickExpr.exec(selector);
                }

                // Match html or make sure no context is specified for #id
                if (match && (match[1] || !context)) {

                    // HANDLE: $(html) -> $(array)
                    if (match[1]) {
                        context = context instanceof jQuery ? context[0] : context;

                        // scripts is true for back-compat
                        // Intentionally let the error be thrown if parseHTML is not present
                        jQuery.merge(this, jQuery.parseHTML(
                            match[1],
                            context && context.nodeType ? context.ownerDocument || context : document,
                            true
                        ));

                        // HANDLE: $(html, props)
                        if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
                            for (match in context) {
                                // Properties of context are called as methods if possible
                                if (jQuery.isFunction(this[match])) {
                                    this[match](context[match]);

                                    // ...and otherwise set as attributes
                                } else {
                                    this.attr(match, context[match]);
                                }
                            }
                        }

                        return this;

                        // HANDLE: $(#id)
                    } else {
                        elem = document.getElementById(match[2]);

                        // Check parentNode to catch when Blackberry 4.6 returns
                        // nodes that are no longer in the document #6963
                        if (elem && elem.parentNode) {
                            // Handle the case where IE and Opera return items
                            // by name instead of ID
                            if (elem.id !== match[2]) {
                                return rootjQuery.find(selector);
                            }

                            // Otherwise, we inject the element directly into the jQuery object
                            this.length = 1;
                            this[0] = elem;
                        }

                        this.context = document;
                        this.selector = selector;
                        return this;
                    }

                    // HANDLE: $(expr, $(...))
                } else if (!context || context.jquery) {
                    return (context || rootjQuery).find(selector);

                    // HANDLE: $(expr, context)
                    // (which is just equivalent to: $(context).find(expr)
                } else {
                    return this.constructor(context).find(selector);
                }

                // HANDLE: $(DOMElement)
            } else if (selector.nodeType) {
                this.context = this[0] = selector;
                this.length = 1;
                return this;

                // HANDLE: $(function)
                // Shortcut for document ready
            } else if (jQuery.isFunction(selector)) {
                return typeof rootjQuery.ready !== "undefined" ?
                    rootjQuery.ready(selector) :
                    // Execute immediately if ready is not present
                    selector(jQuery);
            }

            if (selector.selector !== undefined) {
                this.selector = selector.selector;
                this.context = selector.context;
            }

            return jQuery.makeArray(selector, this);
        };

    
	//init()构造函数最后返回了这个新对象的引用,并用jQuery的原型覆盖了init()的原型。等价于jQuery.prototype.init = function() {...return this;}
    // Give the init function the jQuery prototype for later instantiation
	init.prototype = jQuery.fn;

    // Initialize central reference
    rootjQuery = jQuery(document);	

    新创建的对象无法访问jQuery.prototype中的其他属性,解决方法是:将jQuery.prototype传递jQuery.prototype.init.prototype:     只有jQuery.fn.init的原型指向jQuery.fn(jQuery.prototype),这样我们在使用的时候就能够通过实例化的对象访问到挂载在jQuery.fn上的属性。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

关注
打赏
1665965058
查看更多评论
立即登录/注册

微信扫码登录

0.1199s