marco
marco

Reputation: 1140

"return this" inside a constructor definition: what is its role?

// Q returns new Library object
    var Q = function (params) {
        return new Library(params);
    };

    // In our Library we get our selector with querySelectorAll (we do not support < ie8)
    // We also add selector length, version and twitter/github or whatever you like as information about your library.
    var Library = function (params) {
        // Get params
        var selector = document.querySelectorAll(params),
            i = 0;
        // Get selector length
        this.length = selector.length;
        this.version = '0.1.0';
        this.twitter = 'http://www.twitter.com/mmmmm_';

        // Add selector to object for method chaining
        for (; i < this.length; i++) {
            this[i] = selector[i];
        }

        // Return as object
        return this;        
    };

Why we have return this; at the end of the constructor? What happens if we omit it?

It's not the first time that I find this instruction inside a constructor but sometimes it appears, sometimes (in other classes of other scripts) it doesn't appear and I don't understand the reason.

Upvotes: 2

Views: 67

Answers (3)

hugomg
hugomg

Reputation: 69944

Assuming the constructor is invoked with the new Ctor() syntax, there is no difference if you write return this or not. If the constructor reached the end without returning anything it implicitly returns this.

If you invoke the constructor as a regular function without using new then its going to behave as usual: functions that reach the end without getting to a return statement return undefined and a return this statement will depend on what was the value of the this that got passed in (it will depend on how you call the function).

Upvotes: 5

Arnelle Balane
Arnelle Balane

Reputation: 5487

It returns the current object instance, which allows you to do method-chaining (e.g. object.method1().method2().method3();)

Upvotes: 1

Kristiyan Kostadinov
Kristiyan Kostadinov

Reputation: 3712

It's there so you can chain multiple function on the same object. jQuery does it everywhere.

Upvotes: 0

Related Questions