代码之家  ›  专栏  ›  技术社区  ›  hekevintran

typeof是一个运算符和一个函数

  •  57
  • hekevintran  · 技术社区  · 16 年前

    在javascript中 typeof 是一个运算符和一个函数。它更好地用作运算符还是函数?为什么?

    2 回复  |  直到 16 年前
        1
  •  175
  •   GetFree    10 年前

    typeof 是一个操作员。您可以使用以下方法轻松检查:

    typeof(typeof)
    

    类型 一个函数,此表达式将返回 'function' 但它会导致语法错误:

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

    所以, 类型 不能是函数。可能是括号符号 typeof(foo) 让你觉得 类型 是一个函数,但在语法上,这些括号不是 函数调用 -它们是用来分组的,就像 (2 + 3) *2 . 实际上,您可以添加任意数量的:

    typeof(((((foo))))); // is equal to typeof foo;
    
        2
  •  5
  •   Nick Craver    16 年前

    我认为你是根据清楚度来选择你想要的,作为一个习惯,我通常用它作为一个接线员,方法如下,因为它非常清楚,至少在我看来:

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

    这与此格式相反:

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

    对我来说,读起来有点慢。如果你愿意的话 typeof(thing) 这是同一件事,所以无论什么东西能浮在你的船上。 You can get a full read and what strings to expect from types here .