我正在尝试构建用于学习目的的购物车。我有以下代码
HTML
<div id="MyCart" class="product-cart">
<ul>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</div>
js
var cart = (function () {
cart.createCart = function (cartId) {
console.log(cartId);
cartId = document.getElementById(cartId);
}
return cart;
}());
var shoopingCart = cart.createCart("MyCart");
但是这段代码抛出以下错误
Uncaught TypeError: Cannot set property 'createCart' of undefined
在互联网上花了几个小时并遵循了一些教程后,我对代码做了以下更改,然后它开始工作了。
但是我还是不明白我在这里做了什么
var cart = (function (cart) {
cart.createCart = function (cartId) {
console.log(cartId);
cartId = document.getElementById(cartId);
}
return cart;
}(cart || {}));
var shoopingCart = cart.createCart("MyCart");
有人可以解释一下为什么代码在通过 cart || 后开始工作吗? {}
表达式到匿名函数?一些详细的解释会很好。 :)
最佳答案
所以没有变量传递到范围内。
var cart = (function (cart) {
// can't add a property or method onto undefined.
cart.createCart = function (cartId) {
console.log(cartId);
cartId = document.getElementById(cartId);
}
return cart;
}()); // without any value here ^ cart will be undefined.
var shoopingCart = cart.createCart("MyCart");
但是,如果您将变量传递给上下文:
var cart = (function (cart) {
// cart now is an object which you can attach a property or method
cart.createCart = function (cartId) {
console.log(cartId);
cartId = document.getElementById(cartId);
}
return cart;
}(cart || {})); // pass in cart, or if it is null a new object {}
var shoopingCart = cart.createCart("MyCart");
所以 IIFE 看起来像这样:
(function () { })();
所以忽略 function
你在第二对括号中得到 ( )();
你将参数传递给 function
第一集。这是因为 IIFE 创建了一个全新的干净作用域。这就是我们使用 IIFE 的原因,因为它可以隔离我们在其中使用的全局变量。
所以如果你有这个:
<script>
var someGlobalVariable = "hey";
(function () {
// using someGlobalVariable here will be fine
var myIIFEScopedVariable = "ho";
})();
// trying to access myIIFEScopedVariable here will fail because again, it hasn't been defined here.
</script>
所以 IIFE 非常适合控制作用域中的内容。
购物车|| {}
是一个 JavaScript null 合并,所以它说,传入 cart 但如果它是 null 则给它一个空对象
关于javascript - 使用自调用匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31335894/