jQuery如何在返回数组的同时实现链式函数

How does jQuery chain functions while still returning an array?

本文关键字:实现 函数 返回 数组 jQuery      更新时间:2023-09-26

已阅读

jQuery如何实现命令链?和jquery链是如何工作的?

我仍然想知道像这样的东西在jQuery中是如何可能的

var a = $('body')
// a returns [<body></body>], an array.
a.click()
// Seems like this should return an error if a returns an array, not a function.

链接的SO答案只告诉我如何做像

这样的事情
a.b().c()

这是a()我仍然不明白。我知道,通过返回this链接工作,但它如何也返回一个数组本身?

使用jQuery源代码查看器站点,$ (http://james.padolsey.com/jquery/#v=1.9.1&fn=$)的定义如下:

function (selector, context) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init(selector, context, rootjQuery);
}

注意它是从init()返回的。在init (http://james.padolsey.com/jquery/#v=1.9.1&fn=init)内部,我们看到它在最后调用了一个名为makeArray:

的函数

init

function (selector, context, rootjQuery) {
    var match, elem;
// rest of function defintion
    return jQuery.makeArray(selector, this);
}

这给我们带来了问题的答案'如何jQuery链函数,同时仍然返回一个数组?'

makeArray (http://james.padolsey.com/jquery/#v=1.9.1&fn=jQuery.makeArray)看起来像这样:

makeArray

function (arr, results) {
    var ret = results || [];
    if (arr != null) {
        if (isArraylike(Object(arr))) {
            jQuery.merge(ret, typeof arr === "string" ? [arr] : arr);
        } else {
            core_push.call(ret, arr);
        }
    }
    return ret;
}