Interpretation jquery source (a)

jquery source code interpretation, probably framework to achieve (a)

jquery is a library encapsulates many ways. As it is more convenient to use.

First of all: analysis, first. They have two types of methods,

One is the $ directly call the method. (For example:. $ Each ())

The other is ( S e l e c t O r ) Tone use How to law ( Case Such as ( 'Selector') calling method (e.g.: . 'Div') HTML ())

First implemented, $ ( 'Selector') Method:

<div>1</div>
<div>2</div>
<div>3</div>
<script src="js/jquery-1.7.2.js"></script>
<script>
    // 获得jQuery对象
    console.log($('div'));
</script>

Here Insert Picture Description

Is a return to a class init array. Well first of all we need to return an object.

var jQuery = function(selector) {
    return new init(selector);
}

var init = function(selector) {

}

    // 验证
    console.log(jQuery('div'));

Here Insert Picture Description

However, when exposed another problem, init constructor, it is exposed to the global. Pollute the global variable. (We This is a class library. If the project is a great introduction to our library, found that global variables conflict, and I think this is polluting the global variables.)

This is, we need to put the variable on the object, then you can use jQuery.fn

jQuery.fn = {
    init  : function(selector){
        var doms = document.querySelectorAll(selector);
        for(var i = 0; i < doms.length; i++) {
            this[i] = doms[i];
            // this.length++;
        }
        this.length = doms.length;
        this.selector = selector;
    },
    
}

We know that returns an array of classes.

At this point we need to become like an array of objects, it requires three conditions

1, has length property

2, the index

3, there is a method (e.g. the splice Array) enhancement of the array

(1, has length property

2, the index

3, there is a need for a method (e.g. the splice Array) enhancement array)

jQuery.fn = {
    length: 0,
    splice: Array.prototype.splice,
    init  : function(selector){
        var doms = document.querySelectorAll(selector);
        for(var i = 0; i < doms.length; i++) {
            this[i] = doms[i];
            // this.length++;
        }
        this.length = doms.length;
        this.selector = selector;
    },
    
}
Now perform the final step in changing the point (this step very essence. I feel the essence of jquery in these pointed)
 // 将对象变成类数组
jQuery.fn.init.prototype = jQuery.fn;

So we realized

Often the essence. I feel the essence of jquery in these pointed)

 // 将对象变成类数组
jQuery.fn.init.prototype = jQuery.fn;

So we realized
Here Insert Picture Description

Released seven original articles · won praise 1 · views 186

Guess you like

Origin blog.csdn.net/qq_35898059/article/details/103950260