typeof 关键字代表Javascript 编程中的运算符。
specification 中typeof 运算符的正确定义是:
typeof[(]expression[)] ;
这就是将typeof 用作typeof(expression) 或typeof expression 的原因。
为什么这样实现它可能是为了让开发人员处理其代码中的可见性级别。因此,可以使用 typeof 使用干净的条件语句:
if ( typeof myVar === 'undefined' )
// ...
;
或者使用grouping operator 定义更复杂的表达式:
const isTrue = (typeof (myVar = anotherVar) !== 'undefined') && (myVar === true);
编辑:
在某些情况下,在typeof 运算符中使用括号可以使编写的代码不易产生歧义。
以下面的表达式为例,其中typeof 运算符不带括号。 typeof 会返回空字符串文字和数字之间的连接结果的类型,还是字符串文字的类型?
typeof "" + 42
查看上述运算符的定义和precedence of the operators typeof and +,看来前面的表达式相当于:
typeof("") + 42 // Returns the string `string42`
在这种情况下,在typeof 中使用括号会使您想要表达的内容更加清晰:
typeof("" + 42) // Returns the string `string`