简体   繁体   English

为什么typeof是运算符而不是属性?

[英]Why is typeof an operator instead of a property?

I'm learning Javascript and I ran across something that feels kind of "quirky". 我正在学习Javascript,我遇到了一些“古怪”的东西。

Why isn't typeof a property like .length or .name ? 为什么不输入像.length.name这样的属性? It seems like it should be in that category. 它似乎应该属于那一类。 Instead it's considered an operator sort of like an equals sign = 相反,它被认为是一个类似于等号=的运算符

Maybe there is an obvious explanation or I'm not understanding something (easily possible). 也许有一个明显的解释或我不理解的东西(很容易)。

If it was a property, then you wouldn't be able to test if something was undefined since undefined values can't have properties. 如果它是属性,那么您将无法测试某些内容是否undefined因为未定义的值不能具有属性。

Worse, if a variable was undeclared, then trying to test a property on it would throw a ReferenceError. 更糟糕的是,如果变量未声明,那么尝试在其上测试属性将引发ReferenceError。

Since typeof is universal in JavaScript (that is, you can use it against any variable), it could have been implemented as a property on Object. 由于typeof在JavaScript中是通用的(也就是说,你可以对任何变量使用它),因此它可以作为Object的属性实现。 But, if it were, you wouldn't be able to call it on null and undefined types. 但是,如果是的话,你将无法在nullundefined类型上调用它。

if(someNullVariable.typeof . . .) { . . . } // error

But, because it is an operator, you can use it independent of what you are checking: 但是,因为它是一个操作符,您可以独立于您检查的内容使用它:

if(typeof someNullVariable === "null")  { . . . }  // Match!

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

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