简体   繁体   English

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

[英]typeof is an operator and a function

In JavaScript typeof is an operator and a function. 在JavaScript中, typeof是一个操作符和一个函数。 Is it better used as an operator or a function? 它更适合用作操作员还是功能? Why? 为什么?

typeof is an operator. typeof是一个运营商。 You can easily check it using: 您可以使用以下方法轻松检查:

typeof(typeof)

Were typeof a function, this expression would return 'function' string, but it results in a syntax error: typeof函数,这个表达式将返回'function'的字符串,但它会导致一个语法错误:

js> typeof(typeof);
typein:8: SyntaxError: syntax error:
typein:8: typeof(typeof);
typein:8: .............^

so, typeof cannot be a function. 所以, typeof不能成为一种功能。 Probably parenthesis-notation typeof(foo) made you think typeof is a function, but syntactically, those parenthesis are not function call - they are those used for grouping, just like (2 + 3) *2 . 可能括号 - 符号类型typeof(foo)使你认为typeof是一个函数,但从语法上讲,那些括号不是函数调用 - 它们是用于分组的那些,就像(2 + 3) *2 In fact, you can add any number of them you want: 实际上,您可以添加任意数量的它们:

typeof(((((foo))))); // is equal to typeof foo;

I think you pick which you want based on clarity, as a habit I usually use it as an operator in the following way because it's pretty clear, at least IMO: 我认为你根据清晰度挑选了你想要的东西作为一种习惯,我通常以下面的方式将它用作操作员,因为它非常清楚,至少IMO:

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

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

This is opposed to this format: 这与此格式相反:

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

Which to me, makes it slightly slower to read. 对我而言,它使阅读速度稍慢。 If you do typeof(thing) it's the same thing, so whatever floats your boat. 如果你做类型typeof(thing)它是同样的事情,所以无论什么漂浮你的船。 You can get a full read and what strings to expect from types here . 您可以在此处获得完整的读取以及期望的类型字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM