-->

Why does UnderscoreJS have wrapper functions aroun

2019-07-04 11:10发布

问题:

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.