JQuery.Deferred () - a "new" statement is optional?

How does jQuery implement its deferred object, so the statement newis optional, as in var x = $.Deferred();?

+5
source share
1 answer

Here is a template to achieve this ...

$.Deferred = function() {
    if ( ! (this instanceof $.Deferred)) {
        return new $.Deferred;
    }
}

This works because the thisconstructor is set to a new object. instanceofwill tell you if the LHS operand has an RHS operand in its prototype chain. If this condition is not true, the function will return an instance version of the object.

+6
source

All Articles