Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么我们把变量的值括在括号里?_Javascript_Node.js_Variables - Fatal编程技术网

Javascript 为什么我们把变量的值括在括号里?

Javascript 为什么我们把变量的值括在括号里?,javascript,node.js,variables,Javascript,Node.js,Variables,我见过多个nodejs示例,其中 var minute = (new Date() ). getMinutes(); 是这样定义的。为什么这个日期对象在 var minute = new Date().getMinutes(); works如果没有括号,new关键字(对人而言)可能会模棱两可。i、 e.这是一个新的Date()还是一个新的Date()。getMinutes()让我们测试一下: // let there be function someclass() { console

我见过多个nodejs示例,其中

var minute = (new Date() ). getMinutes();
是这样定义的。为什么这个日期对象在

var minute = new Date().getMinutes();

works

如果没有括号,
new
关键字(对人而言)可能会模棱两可。i、 e.这是一个新的
Date()
还是一个新的
Date()。getMinutes()
让我们测试一下:

// let there be
function someclass()
{
    console.log("constructor"); 
    this.method = function()
    {
       console.log("method");
    }
}

// Trying to call different versions

new test().method()
// Output:
// constructor
// method

(new test()).method()
// Output:
// constructor
// method


// just to be sure:
new Date().getTime() === (new Date()).getTime()
// Output:
true

如图所示和其他人所述,括号在语义上没有必要。

可能是个人选择。除了首选项之外,没有其他理由将这个特定的示例用括号括起来。为了让那些不确定没有括号的版本是否会被这样解释,或者像
new(Date().getMinutes())
这样的人能够立即阅读,我认为@Paulpro的想法是正确的。这里并不含糊,但您可以编写
新日期不带括号,在这种情况下,
new Date.getMinutes()
实际上会被解析器理解为
new(Date.getMinutes())
,这是错误的。这都与可读性有关,最重要的是,操作顺序。记住
PEMDAS
,在决定表达式的求值方式时,括号是优先考虑的。