为什么 UnderscoreJS 有很多原生 Javascript 函数的包装函数? [英] Why does UnderscoreJS have wrapper functions around a lot of native Javascript functions?

查看:17
本文介绍了为什么 UnderscoreJS 有很多原生 Javascript 函数的包装函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 UnderScoreJS 有很多围绕原生 Javascript 函数的包装函数.

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

举个例子:

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

有什么原因吗?或者这些仅仅是为了在使用 underscoreJS 库时确保代码一致性还是只是增强这些功能?

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?

例如,_.isArray 函数可以归结为:

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

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

有什么想法吗?

推荐答案

这是因为并非所有浏览器都提供这些功能.例如,在IE8中尝试Array.isArray,你不会找到它.

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

如今,现代浏览器越来越符合 ECMAScript 标准,这样的垫片"越来越少,但情况并非总是如此!

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!

您会在大多数 Javascript 框架中发现类似的看似多余的函数,以确保它们的任何功能都不会因为给定浏览器中缺少某个函数而引发异常.

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.

还有像 _.each(obj, func) 这样的函数,它们作用于类似数组的对象没有任何问题,而您需要执行 Array.prototype.forEach.call(obj, func)(与实数组的 arr.forEach(func) 相比).所以这是确保 forEach 首先存在的另一个好处.

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.

这篇关于为什么 UnderscoreJS 有很多原生 Javascript 函数的包装函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆