轻松理解jquery源码--元素选择器的实现原理

(function () {
    var jQ = (function () {
        var myJQ = function (selector) {
            return new myJQ.fn.init(selector);
        }

        myJQ.fn = myJQ.prototype = {
            init:function (selector) {
                console.log(selector);
                var ele = document.getElementById(selector.slice(1));
                console.log(ele);
            }
        };

        myJQ.fn.init.prototype = myJQ.fn;
        return myJQ;
    })();
    window.jQ = jQ;
})()

// 使用
jQ('#question-header')
jQ.fn.abc='abc'
jQ('#question-header').abc

从代码可以看出,【挂在】window上的jQ其实是【jQ内部的myJQ的init对象】
myJQ.fn.init.prototype = myJQ.fn
上面是jquery最难理解的,就是把我们使用的jQ的原型设为myJQ,(myJQ.fn.init等于window.jQ),myJQ.fn是myJQ.prototype的【别名】
在这里插入图片描述

(function () {
    var jQ = (function () {
        var myJQ = function (selector) {
            return new myJQ.fn.init(selector);
        }

        myJQ.fn = myJQ.prototype = {
            init:function (selector) {
                this.ele = null; //保存selector取到的对象

                this.html=function(){
                    return ele;
                };
                this.find=function(){
                    ele = document.getElementById(selector.slice(1));
                }
                //find ele from dom tree
                this.find();
            }
        };

        myJQ.fn.init.prototype = myJQ.fn;
        return myJQ;
    })();
    window.jQ = jQ;
})()

jQ('#question-header')
jQ('#question-header').html()

在这里插入图片描述

发布了259 篇原创文章 · 获赞 118 · 访问量 187万+

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/103371942