为什么不使用('function'=== typeof x)而不使用(typeof x ==='function') [英] Why using ('function' === typeof x) and not (typeof x === 'function')
问题描述
在一些开放源代码的JavaScript项目中,我看到人们使用(‘function’=== typeof x)
检查变量是否为函数。我想知道为什么人们用它代替(typeof x ==='function')
。
我觉得第二种方法更自然。是否有充分的理由使用第一种方法?性能?潜在的错误?还是只是风格问题?
这些被称为尤达条件(因为它们听起来像尤达): / p>
有些人喜欢它们,因为如果 = $ c $,则会抛出
作业左侧无效
错误错误地使用了c>而不是 ==
或 ===
。按照最通常的顺序(即 if(count = 5)
,将发生静默分配,这将破坏程序逻辑。
请注意,'function'=== typeof x
不是一个很好的例子;因为 typeof x
将计算为字符串,在这种情况下,不管操作数的顺序如何,放错位置的赋值运算符总是会引发错误。
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?
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.
这篇关于为什么不使用('function'=== typeof x)而不使用(typeof x ==='function')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!