我掌握了 Javascript IIFE 的本质,但是在阅读 this page 时,我对它的用法有点困惑。
听起来以下 JavaScript 模式很常见:
(function(something) {
something.foo = 123;
})(something || something = {})
使用示例:
(function(something) {
something.foo = 123;
})(something || something = {})
console.log(something); // {foo:123}
(function(something) {
something.bar = 456;
})(something || something = {})
console.log(something); // {foo:123, bar:456}
由于 something
是在全局范围内定义的,因此这种模式相对于以下简单代码有什么好处:
var something;
something.foo = 123;
something.bar = 456;
哪种用例才适合使用它?
最佳答案
你得到了一个对something
的闭包,这确保了即使其他一些代码覆盖了它在全局范围内,你仍然拥有对该something
的正确引用,它更好地说明了使用 jQuery 和 jQuery.noConflict();
:
<script src="/path/to/jquery.js"></script>
<script>
(function($) {
// Here $ is jQuery
// Something asynchrone is happening:
setTimeout(function() {
// But $ is still jQuery
}, 1000);
})($);
</script>
<script>
// Someone calls jQuery.noConflict();
jQuery.noConflict();
// And now $ is not jQuery
</script>
关于javascript - 这种基于 IIFE 的 JavaScript 模式有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37749077/