javascript - Why we can't call methods of Date() class without new operator -


this question has answer here:

suppose define variable this

var today = date(); console.log(today.getmonth()); // throw error 

while other class error class call methods without new operator.

function factorial(x) {  if(x <= 1)    throw error("x must not negative");  return x*factorial(x-1); } 

also wrapper objects (number, boolean, string) can call methods without new operator. so, class require new operator or object creation technique before calling methods.

edit: date() string type, should call methods without creating objects. because string type behave if objects. why not?

edit 2: think core function cannot same new date() other functions (array(), string(), error() etc). so, it's hidden feature of language or ecmascript mistake.

ecmascript language specification

according ecmascript specification (on javascript based):

when date called function rather constructor, returns string representing current time (utc).

note function call date(…) not equivalent object creation expression new date(…) same arguments.

reference: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2

calling constructor vs calling function

you need new because creating new date object. calling date() , means calling function returns date() string.

see: http://www.javascripture.com/date

date() : string returns string representation of current date , time. 

in case of other types such array or error, functions factory functions create new object , return them.

see:


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -