具体来说,哪个是正确的?
new Date().getTime();
或
(new Date()).getTime();
由于
答案 0 :(得分:3)
new Date().getTime();
创建()
对象后,getTime
是Date
对象的一种方法,该方法已使用new
运算符进行实例化。
(new Date()).getTime();
与您的第一个版本完全相同。两者都将达到你想要的效果。
答案 1 :(得分:1)
如前所述,两者都是正确的。我想这个问题更多的是关于new
运营商的工作。它的存在可以用这个例子来描述:
var constr = function() {
return {
getConstructor: function() {
return Date
}
};
};
console.log(new constr()); // Object { getConstructor: function }
console.log(new constr().getConstructor); // function () { return Date }
console.log(new constr().getConstructor()); // function Date() { [native code] }
console.log(new (constr().getConstructor())); // Wed Mar 25 2015 20:10:07 GMT+0500 (YEKT)
因此,如果要创建嵌套函数返回的构造函数的实例,则应考虑使用new (code that returns constructor)
而不是new [code that eventually returns constructor]
。后者将无效,因为new
将选择第一个函数调用并创建实例。