Simple implementation record of jQuery and zepto source code

Keywords: Javascript JQuery

This article records jQuery and Zepto's knowledge of some encapsulation libraries of js. I hope to start from this article to learn the language of js and the use of encapsulation on object-oriented and prototype. Let yourself have some progress in js. Mutual encouragement

jQuery Library

The implementation of a simple jQuery Library

You need to understand the concept of closures, immediate function execution, and JavaScript prototypes

(function(window) {
    var jQuery = function(selector) {
        // An object factory can generate new objects in the future without using new. Just execute this method directly
        // The first step is to instantiate a constructor with the new keyword
        return new jQuery.fn.init(selector);
    }
    // Define constructor
    var init = jQuery.fn.init = function(selector) {
        var slice = Array.prototype.slice;
        var dom = slice.call(document.querySelectorAll('*'));
        var i, len = dom.length;
        for(i = 0; i < len; i++) {
            this[i] = dom[i];
        }
        this.length = len;
        this.selector = selector || '';
    }
    
    jQuery.fn = jQuery.prototype = {
        // Change the direction of the constructor
        constructor: jQuery,
        css: function(key, val) {
        
        },
        html: function(val) {
            
        }
    }
    
    // Prototype of connection initialization instance
    // init.prototype = jQuery.fn;
    jQuery.fn.init.prototype = jQuery.fn;
})(window);   
    

Zepto Library

The implementation of simple zepto Library

(function(window) {
    var zepto = {};

    function Z(dom, selector) {
        var i,
      len = dom ? dom.length : 0;
    for(i=0; i<len; i++) {
      this[i] = dom[i]
    }
    this.length = len;
    this.selector = selector || '';
    }

    zepto.Z = function(dom, selector) {
        // Factory method, directly returning an initialization instance
        return new Z(dom, selector);
    }

    zepto.init = function(selector) {
        var slice = Array.prototype.slice;
        var dom = slice.call(document.querySelectorAll('*'));

        return zepto.Z(dom, selector);
    }

    var $ = function(selector) {
        return zepto.init(selector);
    }


    $.fn = {
        // Change the direction of the constructor
        constructor: zepto.Z,
        css: function(key, value) {
          alert('css');
        },
        html: function(value) {
          alert('html')
        }
    }

    Z.prototype = $.fn;

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

Attach the link to be learned:

[several JS code handwritten topics] (https://www.imooc.com/article/23902)


Posted by bigfatpig on Sun, 01 Dec 2019 12:51:42 -0800