问题
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