防止lodash和前端下划线之间的冲突

时间:2016-02-20 05:51:09

标签: javascript underscore.js lodash

似乎没有防止方法来防止前端下划线和lodash之间发生冲突。

我们可以这样做:

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

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

1 个答案:

答案 0 :(得分:10)

关于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>