How does jQuery implement its Deferred object so that new
operator is optional as in var x = $.Deferred();
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With