在JavaScript中使用身份函数 [英] Use of the identity function in JavaScript
问题描述
函数标识(值){
返回值;
$ b $ p
$ b原因是我经常需要区分原始类型( undefined
, null
,布尔值, code>和 string
)和对象类型( object
和 function
>)由 typeof
运算符返回。我觉得使用这个用例的indentity函数非常简单:
if(new identity(value)== value); // value是一个对象类型
if(new identity(value)!= value); //值是原始类型
身份函数比下面的代码小得多:
函数isObject(value){
var type = typeof value;
返回类型==对象||键入==函数;然而,在阅读我的代码时,我的一位朋友抱怨说我的黑客有误导性,比上述替代方案计算量更大。
我不想从我的任何程序中删除此功能,因为我相信这是一个优雅的破解。然后,我再也不为自己编写程序。有没有其他的用例在JavaScript中的身份识别功能?
解决方案我更新了我的 speedtest 来测试是否返回正确的结果......它们不是:
如果与新身份(x)== x
进行比较,则 null
被视为一个对象。 ===
可以工作。
这样的陷阱有利于 isObject ...)
解决方案。
如果您比较 ==='object'
/ 'function'
在 isObject
代码中,那么它的速度将比原始实现快两倍,第三次比新身份(x)=== x
。
快I use the identity function in all my JavaScript programs:
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:
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.
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?
解决方案 I updated my "speedtest" to test if the right results are returned … they aren't:
If you compare with new identity(x) == x
, then null
is deemed an object. ===
works, though.
Such pitfalls speak in favor of the isObject(...)
solution.
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
.
这篇关于在JavaScript中使用身份函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!