Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.Deferred vs new $.Deferred

What is the difference between

var dfd = new $.Deferred

and

var dfd = $.Deferred

In which cases you need to use new vs not using it?

like image 610
mayrop Avatar asked May 14 '13 04:05

mayrop


3 Answers

jQuery official documentation says:

"The jQuery.Deferred() constructor creates a new Deferred object. The new operator is optional."

So I guess usage wise, there is not going to be any difference whether you create a new object from Deferred or use it as it is.

like image 100
Pratheep Avatar answered Oct 31 '22 05:10

Pratheep


These are identical:

var dfd1 = $.Deferred();
var dfd2 = new $.Deferred;
var dfd3 = new $.Deferred();

Each creates a new Deferred object. newis optional because $.Deferred is a factory function.

This is probably nonsense:

var wtf = $.Deferred;

As @ArunPJohny pointed out, it just aliases the factory function. It does not create a Deferred object.

like image 28
Bob Stein Avatar answered Oct 31 '22 05:10

Bob Stein


These two are not equal, one creates a diferred object while another creates an alias

var dfd = new $.Deferred

It create a a deferred object instance, for creating an new instance there is no need to use new keyword - you can just say var dfd = $.Deferred()

var dfd = $.Deferred

It create an alias for the type $.Deferred

So I don't see any need to use the second format in anywhere, expect for if you want to create a shortcut. You can use the first format to create a new instance of deferred object

like image 35
Arun P Johny Avatar answered Oct 31 '22 04:10

Arun P Johny