【问题标题】:Prevent conflict between lodash and underscore on front-end防止前端的lodash和下划线冲突
【发布时间】:2016-02-20 05:51:08
【问题描述】:

似乎没有万无一失的方法来防止前端下划线和lodash之间的冲突。

我们可以这样做:

<script src="/scripts/vendor/underscore/underscore.js"></script>
<script>
    window._us = window._;
    delete window._;
</script>
<script src="/scripts/vendor/lodash/lodash.js"></script>

但这似乎还不够好。有没有办法同时使用这两个库还是我们必须选择?

【问题讨论】:

  • 他们有兼容的API,你为什么要同时使用?
  • 我们正在使用一些来自下划线的函数,这些函数在 lodash 中不存在,例如 _.where
  • Don't underscore 和 lodash 都有 noConflict() 方法? (调用方法,不要手动尝试。)
  • 如果你需要_.where 或者其他lodash 没有的东西,那你为什么不直接用_.mixin 修补它呢?尝试同时使用两者是,IMO,一个错误。
  • 您还可以查看lodash changelogs 以了解如何将下划线的 _.where 等函数替换为兼容的 lodash 函数(消除对下划线依赖的需要)

标签: javascript underscore.js lodash


【解决方案1】:

关于noConflict 的主题,当全局加载下划线或lodash 时,它们将覆盖全局_ 变量。调用noConflict() 将反转这一点,将_ 设置为其先前的值并返回_ 的实例。在下面的示例中,我评论了全局 _ 值在每次操作后将如何变化

<!-- the global _ will now be underscore -->
<script src="/scripts/vendor/underscore/underscore.js"></script>

<!-- the global _ will now be lodash -->
<script src="/scripts/vendor/lodash/lodash.js"></script>

<script>
// the global _ will now be underscore
window.lodash = _.noConflict();

// the global _ will now be undefined
window.underscore = _.noConflict();
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多