JavaScript 中身份函数的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11485508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of the identity function in JavaScript
提问by Aadit M Shah
I use the identity function in all my JavaScript programs:
我在所有 JavaScript 程序中都使用了 identity 函数:
function identity(value) {
return value;
}
The reason is that I often need differentiate between primitives types (undefined
, null
, boolean
, number
and string
) and object types (object
and function
) as returned by the typeof
operator. I feel using the indentity function for this use case very succuint:
原因是我经常需要区分操作符返回的基本类型(undefined
, null
, boolean
, number
and string
)和对象类型(object
and function
)typeof
。我觉得在这个用例中使用 indentity 函数非常简洁:
if (new identity(value) == value); // value is of an object type
if (new identity(value) != value); // value is of a primitive type
The identity function is much smaller and simpler than the following code:
恒等函数比下面的代码更小更简单:
function isObject(value) {
var type = typeof value;
return type == "object" || type == "function";
}
However on reading my code a friend of mine complained that my hack is misleading and more computationally expensive than the above alternative.
然而,在阅读我的代码时,我的一个朋友抱怨我的 hack 具有误导性,并且比上述替代方法在计算上更昂贵。
I don't want to remove this function from any of my programs as I believe it's an elegant hack. Then again I don't write programs solely for myself. Is there any other use case for the identity function in JavaScript?
我不想从我的任何程序中删除这个功能,因为我相信这是一个优雅的黑客。再说一次,我不只是为自己编写程序。JavaScript 中的身份函数还有其他用例吗?
回答by Tomasz Nurkiewicz
IMHO:
恕我直言:
new identity(value) == value
means absolutely nothing and without extra comment I would have to think for a while to figure out what the intent was. On the other hand:
绝对没有任何意义,如果没有额外的评论,我将不得不思考一段时间才能弄清楚意图是什么。另一方面:
isObject(value)
is obvious from the very beginning, no matter how it is implemented. Why can't you use your hack insidea function named isObject()
?
无论如何实施,从一开始就很明显。为什么你不能在名为 的函数中使用你的 hack isObject()
?
BTW More suited for http://codereview.stackexchange.com.
回答by kay - SE is evil
I updated my "speedtest" to test if the right results are returned … they aren't:
我更新了我的“ speedtest”来测试是否返回了正确的结果……它们不是:
If you compare with new identity(x) == x
, then null
is deemed an object. ===
works, though.
如果与 比较new identity(x) == x
,则null
视为对象。===
工作,虽然。
Such pitfalls speak in favor of the isObject(...)
solution.
这些陷阱说明了isObject(...)
解决方案。
If you compare === 'object'
/'function'
in the isObject
code, then it will be double as fast as your original implementation, and almost a third faster than new identity(x) === x
.
如果在代码中比较=== 'object'
/ ,那么它的速度将是原始实现的两倍,比.'function'
isObject
new identity(x) === x