jamie-wilson
jamie-wilson

Reputation: 1925

How to return an Array or an Element all from the same Object? (jQuery)

I am trying to cut down jQuery to a very specific set of functions to use in a product (as well as my general learning). Looking through the source, this seems to be the main structure behind the jQuery library. And it works fantastically.

The big part i can't get my head around, is how jQuery can return an element array, as well as retaining the jQuery object.

Ie, $("body") will return the body in an array, but i can still say $("body").hide() (so i'm essentially calling 'hide' on an array?)

The question: How can I return both an Array AND the jQuery object created in the first function?

var MyNewLibrary = function (selector, context) {
    return new MyNewLibrary.fn.init(selector, context);
};

var $$ = MyNewLibrary;

MyNewLibrary.fn = MyNewLibrary.prototype = 
{
    el: null,
    length: 0,
    selector: "",
    init: function (selector, context) 
    {
        var elem;
        elem = document.getElementById(
                selector[0].substr(1, selector[0].length));

        if (elem) 
        {
            this.length = 1;
            this[0] = elem;
        }

        this.context = document;
        this.selector = selector;
        return this;

    },

    //Example of chained function
    Html: function (str) {
        if (typeof str == "string") {
            this[0].innerHTML = str;
        }
        if (typeof str == "undefined") {
            return this[0].innerHTML;
        }
        return this;
    }

};

MyNewLibrary.fn.init.prototype = MyNewLibrary.fn;

MyNewLibrary.BasicFunction = MyNewLibrary.fn.BasicFunction  = function () 
{
    return "A string returned by $$.BasicFunction()";
};

Upvotes: 2

Views: 267

Answers (1)

Anurag
Anurag

Reputation: 141879

An array is an object, and an object can have functions, so through transitivity, arrays can have functions. If there are multiple results, keep adding them to the newly created object of your library.

this[0] = element1;
this[1] = element2;
// and so on

It's not exactly an array but an array-like object, with a length property and corresponding numeric indexes. jQuery doesn't return an array either, which can be tested with

$("<some selector>") instanceof Array; // false

However, jQuery always returns this array-like object, even when selecting an element by id. In that case an array-like object (the jQuery object) is returned with a single element in it.

Upvotes: 2

Related Questions