为什么要调用没有括号的新日期? [英] Why would you invoke new Date without parentheses?

查看:233
本文介绍了为什么要调用没有括号的新日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚看过这个程式码片段,但不小心在Gmail中开启开发工具:

I have just seen this snippet while accidentally opening dev tools in Gmail:

var GM_TIMING_END_CHUNK1=(new Date).getTime();

我通常会这样想,因为调用没有括号的构造函数是非常不常见的我从来没有见过它直到现在):

I would usually expect something like this, as it's rather uncommon to invoke a constructor without parentheses (at least I have never seen it until now):

var GM_TIMING_END_CHUNK1=new Date().getTime();

var GM_TIMING_END_CHUNK1=Date.now(); //newer browsers

这样做有什么优点,行为有什么不同吗?

Is there any advantage in doing so, any difference in behavior? It's the exact same amount of characters needed, so brevity won't be a reason.

推荐答案

您可以在JS中调用构造函数w

You can invoke constructors in JS w/o the parenthesis if no parameters are to be passed, the effect is the same.

new Date()如果没有参数传递, vs new Date 同样。

new Date() vs new Date the same.

但是,当你想调用一个方法对象:

However, it makes a difference when you want to call a method on the resulting object:

new Date()。getTime()工作,但 new Date.getTime ()不会,因为在后一种情况下,解释器假设 getTime 是Date 类型的方法, true, getTime 是一个实例方法 - 只存在于构造的对象中。为了克服这个问题,你可以在构造函数调用中包含圆括号,告诉解释器它是一个表达式:

new Date().getTime() works but new Date.getTime() would not because in the latter case the interpreter assumes getTime is a method of the Date type but that's not true, getTime is an instance method - only exists in constructed objects. To overcome this you can wrap parenthesis around the constructor call to tell the interpreter that it is an expression:

(new Date).getTime

这样,首先计算表达式,并在结果上调用 getTime 是Date的实例。

This way first the expression is evaluated and getTime is called on the result which is an instance of Date.

这篇关于为什么要调用没有括号的新日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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