TypeError: Date is not a constructor

Pepper Ky picture Pepper Ky · May 8, 2015 · Viewed 24.2k times · Source

So, I've been making forms for my company for some time now with pretty easy Javascript that has worked for me in the past. However all of a sudden it's kicking out the error: TypeError: Date is not a constructor

The Code:

var Date = this.getField("Text1");
Date.value = util.printd("mm/dd/yyyy",new Date());

It works on all my old forms, but now it won't work on new ones... and I've tried making a new button on an old form - just copying and pasting the code, and then it'll break all the other buttons and spit out the same error.

Running: Windows 7 64-bit with Acrobat XI 11.0.10

Answer

ssube picture ssube · May 8, 2015

The variable Date is hiding the global function Date and causing this error. Because of how scoping works in JS, the inner-most use of a name is the one that matters.

In this case, you declare var Date which becomes the only Date the function knows about. When you assign it a field or text (Date = this.getField...), you hide the global class.

You can rename your variable (I would suggest date, as capital names are typically reserved for types) or explicitly reference new window.Date when you go to construct a new date.