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

Ale*_*lls 3 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>
Run Code Online (Sandbox Code Playgroud)

但这似乎不够好.有没有办法使用两个库或我们必须选择?

meg*_*wac 12

关于主题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>
Run Code Online (Sandbox Code Playgroud)