Home  >  Article  >  Web Front-end  >  Front-end advanced (11): Detailed illustration of jQuery objects

Front-end advanced (11): Detailed illustration of jQuery objects

PHPz
PHPzOriginal
2017-04-04 17:58:311224browse

Front-end advanced (11): Detailed illustration of jQuery objects

The accompanying pictures have nothing to do with this article

In the early years of learning the front-end, everyone was very keen on studying the jQuery source code. I still remember that when I learned some application skills from the jQuery source code, I would often be amazed from the bottom of my heart, "It turns out that JavaScript can actually be used like this!"

Although with the development of the front-end , With the rise of several other front-end frameworks, jQuery has gradually become no longer necessary. Therefore, everyone's enthusiasm for jQuery has dropped a lot. But many of the techniques learned from jQuery are still very useful in actual development. A simple understanding of it will also help us understand JavaScript more deeply. The main purpose of this article is to share with you how jquery

object

is encapsulated. It can be regarded as an introduction for everyone to further learn the jQuery source code. When using jQuery objects, we write like this:

// 声明一个jQuery对象
$('.target')

// 获取元素的css属性
$('.target').css('width')

// 获取元素的位置信息
$('.target').offset()

There may be many questions at the beginning of use, such as what is going on with $? Why not use

new

to directly declare an object and so on. After learning about it later, I realized that this is the ingenuity of jQuery object creation. First show it directly with code, and then use pictures to explain to everyone what is going on.

;
(function(ROOT) {

    // 构造函数
    var jQuery = function(selector) {

        // 在jQuery中直接返回new过的实例,这里的init是jQuery的真正构造函数
        return new jQuery.fn.init(selector)
    }

    jQuery.fn = jQuery.prototype = {
        constructor: jQuery,

        version: '1.0.0',

        init: function(selector) {
            // 在jquery中这里有一个复杂的判断,但是这里我做了简化
            var elem, selector;
             elem = document.querySelector(selector);
            this[0] = elem;

            // 在jquery中返回一个由所有原型属性方法组成的数组,我们这里简化,直接返回this即可
            // return jQuery.makeArray(selector, this);
            return this;
        },

        // 在原型上添加一堆方法
        toArray: function() {},
        get: function() {},
        each: function() {},
        ready: function() {},
        first: function() {},
        slice: function() {}
        // ... ...
    }

    jQuery.fn.init.prototype = jQuery.fn;

    // 实现jQuery的两种扩展方式
    jQuery.extend = jQuery.fn.extend = function(options) {

        // 在jquery源码中会根据参数不同进行很多判断,我们这里就直接走一种方式,所以就不用判断了
        var target = this;
        var copy;

        for(name in options) {
            copy = options[name];
            target[name] = copy;
        }
        return target;
    }

    // jQuery中利用上面实现的扩展机制,添加了许多方法,其中

    // 直接添加在构造函数上,被称为工具方法
    jQuery.extend({
        isFunction: function() {},
        type: function() {},
        parseHTML: function() {},
        parseJSON: function() {},
        ajax: function() {}
        // ...
    })

    // 添加到原型上
    jQuery.fn.extend({
        queue: function() {},
        promise: function() {},
        attr: function() {},
        prop: function() {},
        addClass: function() {},
        removeClass: function() {},
        val: function() {},
        css: function() {}
        // ...
    })

    // $符号的由来,实际上它就是jQuery,一个简化的写法,在这里我们还可以替换成其他可用字符
    ROOT.jQuery = ROOT.$ = jQuery;

})(window);

In the above code, I encapsulate a simplified version of the jQuery object. It briefly shows everyone the overall framework of jQuery. If you understand the overall framework, it will be very easy for everyone to read the jQuery source code.

We can see in the code that jQuery itself uses some clever syntax for prototype processing, such as

jQuery.fn = jQuery.prototype

, jQuery.fn.init .prototype = jQuery.fn;, etc. These few sentences are the key to the official jQuery object. I will use pictures to show you what the logic is.

Front-end advanced (11): Detailed illustration of jQuery objects
jQuery Object Core Diagram

Object Encapsulation Analysis

In the above implementation, the code First, declare a fn attribute in the jQuery constructor and point it to the prototype

jQuery.prototype

. And added init method in prototype. <pre class="brush:php;toolbar:false">jQuery.fn = jQuery.prototype = {     init: {} }</pre>Then the init prototype was pointed to jQuery.prototype.

jQuery.fn.init.prototype = jQuery.fn;

In the constructor jQuery, the instance object of init is returned.

var jQuery = function(selector) {

    // 在jQuery中直接返回new过的实例,这里的init是jQuery的真正构造函数
    return new jQuery.fn.init(selector)
}

When the entrance is finally exposed to the outside world, the characters

$

and jQuery are equated. <pre class="brush:php;toolbar:false">ROOT.jQuery = ROOT.$ = jQuery;</pre>So when we directly use

$('#test')

to create an object, we actually create an instance of init. The real thing here is The constructor is the init method in the prototype.

Note:

Many friends who don’t know much about the internal implementation of jQuery often use $() without restraint when using jQuery, for example, for the same Different operations of elements: <pre class="brush:php;toolbar:false">var width = parseInt($('#test').css('width')); if(width &gt; 20) {     $('#test').css('backgroundColor', 'red'); }</pre>Through our series of analysis above, we know that every time we execute

$()

, an instance object of init will be regenerated, so when we It is very incorrect to use jQuery without restraint. Although it seems more convenient, it consumes a lot of memory. The correct approach is that since it is the same object, then use a variable to save it for subsequent use.

var $test = $('#test');
var width = parseInt($test.css('width'));
if(width > 20) {
    $test.css('backgroundColor', 'red');
}

Extension method analysis

In the above code implementation, I also simply implemented two extension methods.

jQuery.extend = jQuery.fn.extend = function(options) {

    // 在jquery源码中会根据参数不同进行很多判断,我们这里就直接走一种方式,所以就不用判断了
    var target = this;
    var copy;

    for(name in options) {
        copy = options[name];
        target[name] = copy;
    }
    return target;
}

To understand its implementation, we must first clearly know the point of this. If you are not sure, you can go back and read our previous explanation about this pointing. The parameter options object passed in is an object in the

key: value<a href="http://www.php.cn/wiki/1051.html" target="_blank"> mode. I traverse the options through </a>for in, using key as a new attribute of jQuery and value as The new methods corresponding to this new attribute are added to jQuery methods and jQuery.fn respectively. That is to say, when we extend jQuery through

jQuery.extend

, the method is added to the jQuery constructor, and when we pass jQuery.fn.extend When extending jQuery, methods are added to the jQuery prototype. In the above example, I also briefly showed that within jQuery, the implementation of many methods is completed through these two extension methods.

当我们通过上面的知识了解了jQuery的大体框架之后,那么我们对于jQuery的学习就可以具体到诸如css/val/attr等方法是如何实现这样的程度,那么源码学习起来就会轻松很多,也会节约更多的时间。也给一些对于源码敬而远之的朋友提供了一个学习的可能。

有一个朋友留言给我,说她被静态方法,工具方法和实例方法这几个概念困扰了很久,到底他们有什么区别?

其实在上一篇文章中,关于封装一个对象,我跟大家分享了一个非常非常干货,但是却只有少数几个读者老爷get到的知识,那就是在封装对象时,属性和方法可以具体放置的三个位置,并且对于这三个位置的不同做了一个详细的解读。

而在实现jQuery扩展方法的想法中,一部分方法需要扩展到jQuery构造函数中,一部分方法需要扩展到原型中,当我们通读jQuery源码,还发现有一些方法放在了模块作用域中,至于为什么会有这样的区别,建议大家回过头去读读前一篇文章。

而放在构造函数中的方法,因为我们在使用时,不需要声明一个实例对象就可以直接使用,因此这样的方法常常被叫做工具方法,或者所谓的静态方法。工具方法在使用时因为不用创建新的实例,因此相对而言效率会高很多,但是并不节省内存。

而工具方法的特性也和工具一词非常贴近,他们与实例的自身属性毫无关联,仅仅只是实现一些通用的功能,我们可以通过$.each$('p').each这2个方法来体会工具方法与实例方法的不同之处。

在实际开发中,我们运用得非常多的一个工具库就是lodash.js,大家如果时间充裕一定要去学习一下他的使用。

$.ajax()
$.isFunction()
$.each()
... ...

而放在原型中的方法,在使用时必须创建了一个新的实例对象才能访问,因此这样的方法叫做实例方法。也正是由于必须创建了一个实例之后才能访问,所以他的使用成本会比工具方法高很多。但是节省了内存。

$('#test').css()
$('#test').attr()
$('p').each()

这样,那位同学的疑问就很简单的被搞定了。我们在学习的时候,一定不要过分去纠结一些概念,而要明白具体怎么回事儿,那么学习这件事情就不会在一些奇奇怪怪的地方卡住了。

所以通过$.extend扩展的方法,其实就是对工具方法的扩展,而通过$.fn.extend扩展的方法,就是对于实例方法的扩展。那么我们在使用的时候就知道如何准确的去使用自己扩展的方法了。

jQuery插件的实现

我在初级阶段的时候,觉得要自己编写一个jQuery插件是一件高大上的事情,可望不可即。但是通过对于上面的理解,我就知道扩展jQuery插件其实是一件我们自己也可以完成的事情。

在前面我跟大家分享了jQuery如何实现,以及他们的方法如何扩展,并且前一篇文章分享了拖拽对象的具体实现。所以建议大家暂时不要阅读下去,自己动手尝试将拖拽扩展成为jQuery的一个实例方法,那么这就是一个jQuery插件了。

具体也没有什么可多说的了,大家看了代码就可以明白一切。

// Drag对象简化代码,完整源码可在上一篇文章中查看
;
(function() {

    // 构造
    function Drag(selector) {}


    // 原型
    Drag.prototype = {
        constructor: Drag,

        init: function() {
            // 初始时需要做些什么事情
            this.setDrag();
        },

        // 稍作改造,仅用于获取当前元素的属性,类似于getName
        getStyle: function(property) {},

        // 用来获取当前元素的位置信息,注意与之前的不同之处
        getPosition: function() {},

        // 用来设置当前元素的位置
        setPostion: function(pos) {},

        // 该方法用来绑定事件
        setDrag: function() {}
    }

    // 一种对外暴露的方式
    window.Drag = Drag;
})();

// 通过扩展方法将拖拽扩展为jQuery的一个实例方法
(function ($) {
  $.fn.extend({
    becomeDrag: function () {
      new Drag(this[0]);
      return this;   // 注意:为了保证jQuery所有的方法都能够链式访问,每一个方法的最后都需要返回this,即返回jQuery实例
    }
  })
})(jQuery);

后续文章内容一个大概预想

去年年末的时候就有了想要将JavaScript基础知识总结一下的这样一个想法,可是JavaScript基础知识确实并非全部是层层递进的关系,有很多碎片化的东西,所以之前一直没有找到一个合适的整理方法。

直到在segmentfault中我在给题主建议如何快速学习一门诸如react/vue这样的流行框架时,找到了一个好一点的思路,于是就有了这样一系列文章,虽然它并不全面,很多知识没有涉及到,但是其实我是围绕最终通过模块化来构建自己代码这样一个思路来总结的,因此这系列文章能够解决大家最核心的问题。

也正因为如此,这系列的文章的终点将会是在ES6环境下掌握react的使用。虽然前面我多多少少都涉及到了模块的一些概念,但是还差一个实践。因此最终我会以ES6的模块跟大家分享如何使用。

那么后续的文章应该会涉及的内容,就大概包括:

  • 事件循环机制

  • Promise

  • ES6的基础语法

  • Commonly used design patterns under ES6

  • ES6 module

  • Combined with ES6 Example

  • React basic syntax

  • React component

  • React high-order component

  • React Example

  • Redux

This series of articles can be regarded as a concrete and practical guide for everyone’s learning direction. A feasible guide, rather than simply telling you how to learn through chicken soup. So, friends who want to learn this knowledge, come and follow me! ! ! !

The above is the detailed content of Front-end advanced (11): Detailed illustration of jQuery objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn