为什么不使用('function'=== typeof x)而不使用(typeof x ==='function') [英] Why using ('function' === typeof x) and not (typeof x === 'function')

查看:138
本文介绍了为什么不使用('function'=== typeof x)而不使用(typeof x ==='function')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些开放源代码的JavaScript项目中,我看到人们使用(‘function’=== typeof x)检查变量是否为函数。我想知道为什么人们用它代替(typeof x ==='function')



我觉得第二种方法更自然。是否有充分的理由使用第一种方法?性能?潜在的错误?还是只是风格问题?

解决方案

这些被称为尤达条件(因为它们听起来像尤达): / p>



有些人喜欢它们,因为如果 = 作业左侧无效错误错误地使用了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆