为什么我们不能调用Date()类的方法没有new运算符 [英] Why we can't call methods of Date() class without new operator

查看:178
本文介绍了为什么我们不能调用Date()类的方法没有new运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了一个这样的变量:

Suppose I define a variable like this

var today = Date();
console.log(today.getMonth()); // Throw Error

而其他类就像Error类调用他们没有new运算符的方法。

while other class like Error class call their methods without new operator.

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

此外,包装器对象(数字,布尔值,字符串)运算符。
所以,这是唯一的类,在调用他们的方法之前需要new操作符或任何对象创建技术。

Also wrapper objects (number, boolean, string) can call their methods without new operator. So, Is this the only class which require new operator or any object creation technique before calling their methods.

编辑: Date()是一个字符串类型,所以它应该调用他们的方法,而不创建对象。因为字符串类型的行为好像它们是对象。那么为什么不呢?

As Date() is a string type, so it should be call their methods without creating objects. Because string type behave as if they are objects. So why not?

编辑2 :我认为这是唯一不能与 ()像其他函数( Array(),String(),Error()等)。因此,这也是此语言的隐藏功能或ECMAScript错误。 p>

Edit 2: I think this is the only core function which cannot be same as new Date() like other functions (Array(), String(), Error() etc). So, it's also the hidden feature of this language or ECMAScript mistake.

推荐答案

ECMAScript语言规范



根据ECMAScript规范(基于Javascript):

ECMAScript Language Specification

According to the ECMAScript specification (on which Javascript is based):


当Date作为函数而不是作为构造函数调用时,
返回一个表示当前时间(UTC)的字符串。

When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC).

注意函数调用Date(...)不等同于对象
创建表达式具有相同参数的新日期(...)。

NOTE The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments.

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

您需要 code>,因为您正在创建一个新的 Date 对象。
调用简单的Date(),意味着调用以字符串形式返回Date()的函数。

You need the new because you are creating a new Date object. Calling simply Date() , means calling a function that returns the Date() as a string.

参见: http://www.javascripture.com/Date

Date() : String
Returns a string representation of the current date and time.

在Array或Error等其他类型的情况下,函数是创建一个新的对象并返回它们。

In the case of other types such as Array or Error, the functions are factory functions that create a new object and return them.

查看:

错误(message:String):错误
创建一个新的错误描述错误的指定消息。

Error(message : String) : Error Creates a new Error with the specified message that describes the error.

new错误$ b与错误(消息)相同

new Error(message : String) : Error Same as Error(message)

这篇关于为什么我们不能调用Date()类的方法没有new运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆