1

I've been going through the jQuery code and I have seen a few links that have this question. I am asking it again because I did not really understand any of them so please do not mark this question as duplicate. I've gone through the following stackoverflow links:

How can jQuery return an array and still have it to be a jQuery object

How does jQuery chaining work

How does jQuery return an array of the selected objects

Gone through all of those links and I do not get how it works. All I ask is a very simple example of returning an array from a constructor object and still chaining it. I have tried the following code:

(function(window, document, undefined)
{
    var lhd = function(selector)
    {
        return new Lhd(selector);
    }

    function Lhd(selector)
    {
        var elem = document.querySelectorAll(selector),
            elems = {};

        return this.makeArray(elems, elem);
    }

    Lhd.prototype = {
        makeArray: function(arr, result)
        {
            var ret = result || [];

            Array.prototype.push.apply(ret, arr);

            return ret;
        },

        click: function()
        {
            console.log('click');

            return this;
        }
    };

    window.lhd = lhd;
})(window, document);

I'm able to return an array but unable to chain it.

10
  • 2
    you shouldn't return from a constructor. Commented Jul 23, 2015 at 1:45
  • makeArray returns not this but something else. How are you going to chain it? Commented Jul 23, 2015 at 1:47
  • the makeArray is returning the same as the jQuery code returns @zerkms Commented Jul 23, 2015 at 1:51
  • @DanielA.White, please elaborate more. How should I go about to chain it? Commented Jul 23, 2015 at 1:51
  • @Hawk if it is returning the same as jquery then it should work the same as jquery. If it works - why do you ask the question? Commented Jul 23, 2015 at 1:55

1 Answer 1

1

I'm able to return an array

You must not return an array, you must make the new instance (this) become array-like.

function lhd(selector) {
    return new Lhd(selector);
}

function Lhd(selector) {
    var elems = document.querySelectorAll(selector);

    this.length = 0; // initialise a length
    Array.prototype.push.apply(this, elems); // push onto the instance

    // don't `return` anything - it's a constructor
}

Lhd.prototype.click = function() {
    console.log('click');
    return this;
};

You can use it now like lhd('a').click().click().

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, I was frying my mind for the past 2 days. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.