Why using ('function' === typeof x) and not (typeof x === 'function') [closed]

孤人 提交于 2020-01-04 15:53:33

问题


In some open source JavaScript projects, I saw people checking if a variable is a function or not with ('function' === typeof x). I wonder why people use that instead of (typeof x === 'function').

I feel the second way is more natural. Is there any good reason to use the first way? Performance? Error potential? Or is it just a matter of style?


回答1:


These are called "Yoda Conditions" (because they sound like Yoda):

Some people prefer them, because an Invalid left-hand side in assignment error will be thrown if = is used by mistake instead of == or ===. In the most usual order (i.e., if(count = 5), a silent assignment will happen, and will screw up the program logic.

Note that 'function' === typeof x is not a good example; since typeof x will evaluate to a string, a misplaced assignment operator will always throw an error in this case, regardless of the order of the operands.




回答2:


They are identical expressions. When you compare with == or ===, it doesn't matter what is on which side of the expression.

if(null === myVar)

if('hello' === str)

etc. are all valid.

If one of two expressions is quite long, you may want to put it on the right hand side so it's easier for the eye to see what is being compared.




回答3:


There is no probably no reason but it might historically come from the = and == difference, where it does matter. See the thing with

if (a = 5)

and

if (5 = a)

is that the first one doesn't check if a is 5, it assigns 5 to a. So people came up with the reverse check, which throws compile errors, since you cannot assign to 5, etc. This way you can fix your code if you forgot one =. So it might be for consistency purposes as well.




回答4:


They are identical. Some Java programmers tend to write it this way as an usual best practice in Java to write null != object.getSomething() instead of object.getSomeThing() != null. This is for avoiding the possible NullPointer

But, in Javascript this makes no sense. And as you pointed, (typeof x === 'function') is the natural way.



来源:https://stackoverflow.com/questions/15094506/why-using-function-typeof-x-and-not-typeof-x-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!