How Does Jquery Chain Functions While Still Returning An Array?
Having read How does jQuery accomplish chaining of commands? and how does jquery chaining work? I am still left to wonder how something like this is possible in jQuery var a = $('
Solution 1:
Using the jQuery source code viewer site the definition for $ (http://james.padolsey.com/jquery/#v=1.9.1&fn=$) is as follows:
$
function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'returnnew jQuery.fn.init(selector, context, rootjQuery);
}
Notice it is returning from init(). Inside of init (http://james.padolsey.com/jquery/#v=1.9.1&fn=init) we see that at the end it calls a function called makeArray:
init
function (selector, context, rootjQuery) {
var match, elem;
// rest of function defintionreturn jQuery.makeArray(selector, this);
}
Which brings us to the answer to the question 'How does jQuery chain functions while still returning an array?'
makeArray (http://james.padolsey.com/jquery/#v=1.9.1&fn=jQuery.makeArray) looks like this:
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;
}
Post a Comment for "How Does Jquery Chain Functions While Still Returning An Array?"