编程语言
首页 > 编程语言> > javascript – jQuery如何完成命令的链接?

javascript – jQuery如何完成命令的链接?

作者:互联网

我认为自己(充其量)是一个中级JavaScript人……当然……我想了解一些事情是如何完成的,所以我可以编写更好的代码.因此,我一直在寻找jQuery的底层,试图更多地了解它如何完成某些事情.

例如:
jQuery处理IE和Opera通过执行以下操作按名称而不是ID返回项目的情况:

// HANDLE: $("#id")
else 
{
    var elem = document.getElementById( match[3] );

    // Handle the case where IE and Opera return items
    // by name instead of ID
    if ( elem && elem.id != match[3] )
        return jQuery().find( selector );

    // Otherwise, we inject the element directly into the jQuery object
    var ret = jQuery( elem || [] )
    ret.context = document;
    ret.selector = selector;

    return ret;
}

……好吧,这很容易!

但是一个典型的jQuery代码链将一系列命令链接在一起:

$('#someElementId').fadeIn().css({ ...Some CSS Properties ... });

现在……我认为’链接部分在以下区域处理:

jQuery.extend = jQuery.fn.extend = function() { ... };

我正在梳理这个区域……我看到如何处理单个命令……但我并没有真正看到WHERE或如何管理命令链.所以我显然错过了一些东西.

所以我的问题是:

> jQuery如何实现选择器的链接?

解决方法:

根据你的评论:

这是来自这里的例子:http://en.wikipedia.org/wiki/Fluent_interface#JavaScript
有额外的评论

var Car = function() {

        var speed, color, doors;

        this.setSpeed = function(speed) {
                this.speed = speed;
                **//Returns the reference to the calling `car` object** 
                return this; 
        };

        this.setColor = function(color) {
                this.color = color;
                **//Returns the reference to the calling `car` object** 
                return this; 
        };

        this.setDoors = function(doors) {
                this.doors = doors;
                **//Returns the reference to the calling `car` object** 
                return this; 
        };

};

// Fluent interface
**//Each method returns a reference to the object itself**
**//so the next method chain is refering back to the previous returned value**
**//ie - itself, the orginal object that started the call chain**
myCar = new Car();
myCar.setSpeed(100).setColor('blue').setDoors(5);

// Example without fluent interface
**// normal, non fluent style, where each method returns Void**
**// so you need to start with the object reference yourself each time**
myCar2 = new Car();
myCar2.setSpeed(100);
myCar2.setColor('blue');
myCar2.setDoors(5);

标签:chaining,javascript,jquery
来源: https://codeday.me/bug/20190723/1514384.html