javascript - 为什么我们不能在没有 new 运算符的情况下调用 Date() 类的方法

标签 javascript date constructor

<分区>

假设我这样定义一个变量

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

而像 Error 类这样的其他类在没有 new 运算符的情况下调用它们的方法。

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

包装器对象(数字、 bool 值、字符串)也可以在没有 new 运算符的情况下调用它们的方法。 那么,这是唯一一个在调用它们的方法之前需要 new 运算符或任何对象创建技术的类吗。

编辑: 由于 Date() 是字符串类型,所以应该在不创建对象的情况下调用它们的方法。因为字符串类型的行为就好像它们是对象一样。那为什么不呢?

编辑 2:我认为这是唯一不能像其他函数一样与 new Date() 相同的核心函数(Array(), String( ), 错误() 等)。所以,它也是 hidden这种语言的特性或 ECMAScript 错误。

最佳答案

ECMAScript 语言规范

根据 ECMAScript 规范(Javascript 的基础):

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

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

调用构造函数与调用函数

您需要 new 因为您正在创建一个新的 Date 对象。 简单地调用 Date() 意味着调用一个将 Date() 作为字符串返回的函数。

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

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

对于 Array 或 Error 等其他类型,函数是创建新对象并返回它们的工厂函数。

参见:

关于javascript - 为什么我们不能在没有 new 运算符的情况下调用 Date() 类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16544001/

相关文章:

javascript - 当我尝试向托管账户付款时出现错误

javascript - Angular Js - 更改 View 不起作用

JAVA - 它是 java.util.Calendar 类中的错误还是什么?

具有范围限制的 Java 类构造函数参数

c++ - 无法让构造函数运行

javascript - 将 .apply() 与 'new' 运算符一起使用。这可能吗?

javascript - 选择随机 <li> 元素

php - 处理mysql中的日期?

ios - 我怎样才能找到下周末的 swift

javascript - 仅通过 jQuery/Javascript 修复定位 div