gpt4 book ai didi

javascript - 防止前端lodash和下划线冲突

转载 作者:行者123 更新时间:2023-12-01 07:36:15 24 4
gpt4 key购买 nike

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

我们可以这样做:

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

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

最佳答案

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

关于javascript - 防止前端lodash和下划线冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35519704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com