假设我这样定义一个变量
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 等其他类型,函数是创建新对象并返回它们的工厂函数。
参见: