Use of the identity function in JavaScript

瘦欲@ 提交于 2020-01-13 03:56:23

问题


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?


回答1:


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.




回答2:


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 inside a function named isObject()?

BTW More suited for http://codereview.stackexchange.com.



来源:https://stackoverflow.com/questions/11485508/use-of-the-identity-function-in-javascript

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