0

Can I kindly ask for explanation:

What does the code below represent? Does it create a DndUpload Ojbect? Or, does it create a DndUpload() function? What I miss is the statement new normally present during JavaScript objects creation. Can I kindly ask for some explanation, as I am confused.

var DndUpload = function (inputElem)
{
    this.input = inputElem;
    this.dropZone = null;
    this.isDragging = false;
    this.init();
};

As far as I know this is the way to create object in Javascript:

var myObject = new function()
{
};

If you have any link with explanation, that would help. Thank you.

Bunkai.Satori
  • 4,698
  • 13
  • 49
  • 77
  • 1
    Your answer is in here : http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – totten Sep 10 '12 at 20:27
  • @EnesUnal: +1, hi and thanks for your great comment. That helped, although the explanations in the *Answers* section were very helpful too. – Bunkai.Satori Sep 10 '12 at 20:39

3 Answers3

2

It's a worse way of writing this:

function DndUpload(inputElem)
{
    this.input = inputElem;
    this.dropZone = null;
    this.isDragging = false;
    this.init();
}

which is a function declaration. It does not create an instance of DndUpload. Technically, it does create an object – its name is DndUpload and it is an instance of Function. To create an instance of this "class:"

var instance = new DndUpload(document.getElementById('someInputId'));
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • +1, thank you for immediate answer. This is an excellent explanation. It clearly answers my question. Thank you for the additional links you provided. They add value to your answer. – Bunkai.Satori Sep 10 '12 at 20:48
1

the code you have essentially creates a constructor for a "class" it's more or less a blueprint for an object.

It then puts that constructor into a variable called DndUpload

So you can now make an object with

var myObject = new DndUpload(input elem)
1
var myObject = new function()
{
};

Defines an anonymous constructor function and then instantiates a new object using the anonymous constructor function. It could have been replaced with var myObject = {}.

var DndUpload = function (inputElem)
{
    this.input = inputElem;
    this.dropZone = null;
    this.isDragging = false;
    this.init();
};

Defines a constructor function (technically an anonymous constructor function assigned to a variable). You can then create objects of this "class" by invoking the constructor function with new:

var dndUploadObject = new DnDUpload(),
    anotherUploadObject = new DnDUpload(); //2 unique DnDUpload objects
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • +1, hi. Thanks for the answer. Despite all of the answer were excellent, in my opinion, this answer describes my question the best. Especially the information on anonymous constructors was new to me. I am marking this answer as the *Accepted Answer*. Thank you again. – Bunkai.Satori Sep 10 '12 at 20:51