Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.Deferred() - "new" operator is optional?

How does jQuery implement its Deferred object so that new operator is optional as in var x = $.Deferred(); ?

like image 551
gsklee Avatar asked Aug 13 '12 07:08

gsklee


1 Answers

Here is a pattern to achieve that...

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

It works because this in a constructor is set to the new object. instanceof will tell you if the LHS operand has the RHS operand in its prototype chain. If this condition isn't true, the function will return an instantiated version of the object.

like image 87
alex Avatar answered Sep 30 '22 15:09

alex