Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I found Date can be used without the new keyword.

Date(1)
> "Thu May 28 2015 15:54:20 GMT+0800 (CST)"
new Date(1)
> Thu Jan 01 1970 08:00:00 GMT+0800 (CST)

I was wondering whether there is any side-effect of using it without new.. Why would it be designed like this?

share|improve this question
2  
Answer 1: stackoverflow.com/questions/383402/… Answer 2: JavaScript was (mis-)designed in a terrible hurry - mere 10 days. –  Den May 28 at 8:08
    
Short answer: because it may not be supported in future versions. That should be plenty reason to prefer using new. –  Neil May 28 at 8:43
1  
possible duplicate of Fundamental Difference between fn() and new fn() in javascript –  gnat May 28 at 8:59

1 Answer 1

In JavaScript a constructor is just an ordinary function. Any function which can be called as a constructor with 'new' can be called as an ordinary function. But functions will almost always be written as either a constructor or non-constructor function, and using it the other way is an error.

The built-in objects however are specifically designed so that you can use them both ways (as constructor and as ordinary functions) with two different results. For example new Date(1) creates a new Date object (as you would expect for a constructor) while Date(1) returns a string representation of the corresponding date, which is perhaps more surprising.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.