typeof是一个操作符和一个函数

hek*_*ran 58 javascript

在JavaScript中typeof是一个运算符和一个函数.它更适合用作操作员还是功能?为什么?

el.*_*ado 179

typeof是一个运营商.您可以使用以下方法轻松检查:

typeof(typeof)
Run Code Online (Sandbox Code Playgroud)

如果typeof是函数,此表达式将返回'function'字符串,但会导致语法错误:

js> typeof(typeof);
typein:8: SyntaxError: syntax error:
typein:8: typeof(typeof);
typein:8: .............^
Run Code Online (Sandbox Code Playgroud)

所以,typeof不能成为一种功能.可能括号 - 符号typeof(foo)使你认为typeof是一个函数,但从语法上讲,这些括号不是函数调用 - 它们是用于分组的,就像(2 + 3) *2.实际上,您可以添加任意数量的它们:

typeof(((((foo))))); // is equal to typeof foo;
Run Code Online (Sandbox Code Playgroud)

  • 注意这适用于其他运算符 - `[] instanceof(Object)`. (5认同)

Nic*_*ver 5

我认为你根据清晰度挑选了你想要的东西作为一种习惯,我通常以下面的方式将它用作操作员,因为它非常清楚,至少IMO:

if(typeof thing === "string") { 
  alert("this is a string");
}

if(typeof thing === "function") {
  alert("this is a function");
}
Run Code Online (Sandbox Code Playgroud)

这与此格式相反:

if(typeof(thing) === "string") { 
  alert("this is a string");
}
Run Code Online (Sandbox Code Playgroud)

对我而言,它使阅读速度稍慢.如果你这样做typeof(thing)是相同的,所以无论什么漂浮你的船. 您可以在此处获得完整的读取以及期望的类型字符串.

  • 难道这个答案不应该明确地说"`typeof`总是一个运算符"或"`typeof`不是函数"?`我通常用它作为操作员` - 它总是**一个操作员,不是吗?我的意思是,我们没有选择,是吗? (12认同)