0
var a = Date;
Object.defineProperty(window, "Date", { get: function() { console.log(this); return a; } });

(new Date);
Date();

How can I know, when Date is being called as a constructor(with "new"), and when it's being called as a function?

Update
these answers don't work for this case.
this is always equal to a window

Community
  • 1
  • 1
cepB
  • 1
  • 2
  • You need () after new Date, just saying – Jay Jun 09 '16 at 01:21
  • 1
    @Wade: You don't when you use `new` – Bergi Jun 09 '16 at 01:24
  • 2
    Notice that the getter you defined is always invoked on the global object. Only the function that is called can really distinguish between constructor and function calls. – Bergi Jun 09 '16 at 01:25
  • @Bergi sorry, need is a strong word. Isn't it convention though? – Jay Jun 09 '16 at 01:32
  • @Wade: I don't think it's a convention, it's just that most of the constructor invocations you see are with arguments and you need the parentheses for those. – Bergi Jun 09 '16 at 01:34
  • Per [*ECMA-262 §20.3.2*](http://www.ecma-international.org/ecma-262/6.0/#sec-date-constructor): "*When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC).*". When called as a constructor, it must return an object. When called as a function, it will return a string. If you replace the global *Date* property with some other function, all bets are off. – RobG Jun 09 '16 at 01:37
  • @Bergi oh, everyone I've ever worked with has defined it to be convention haha. Since yeah you have to have parentheses when you have arguments, it makes sense to use an empty set of parentheses, so that it mimics how function calls work. That is, you always use parentheses – Jay Jun 09 '16 at 01:37
  • Just as a note, I think in ES2015 you can check if (new^), which returns whether it was called with the new keyword – Jay Jun 09 '16 at 02:01

1 Answers1

-2

Date is a Constructor function. It's just like any JavaScript Constructor. You will alway need to use new when you use it.

JavaScript Date

andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
  • Very untrue. You NEVER strictly have to use new unless explicitly defined inside of the function. – Jay Jun 09 '16 at 02:00