Why does UnderscoreJS have wrapper functions around a lot of native Javascript functions?

≯℡__Kan透↙ 提交于 2020-01-04 01:55:09

问题


I noticed that UnderScoreJS has a lot of wrapper functions around native Javascript functions.

Take for example:

_.isArray, _.isBoolean, _.isNaN?

Is there any reason for this? Or are these simply meant for ensuring code consistency when using an underscoreJS library OR just enhancing these functions in anyway?

For example, the _.isArray function gets down to this:

_.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === '[object Array]';
  };

Any idea?


回答1:


It's because those functions are not present in all browsers. For example, try Array.isArray in IE8 and you won't find it.

Nowadays modern browsers are getting more up to date with the ECMAScript standard and such "shims" are less and less needed, but it was not always the case!

You will find similar seemingly redundant functions in most Javascript frameworks to ensure that none of their feature throws an exception because a function is missing in a given browser.

There are also functions like _.each(obj, func) that act on array-like objects without any problems while you would need to do Array.prototype.forEach.call(obj, func) (compared to arr.forEach(func) for a real array). So that's another benefit on top of making sure that forEach is present in the first place.



来源:https://stackoverflow.com/questions/25166394/why-does-underscorejs-have-wrapper-functions-around-a-lot-of-native-javascript-f

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