I am trying to build a shopping cart for learning purpose. I have following codes
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");
But this code throws following error
Uncaught TypeError: Cannot set property 'createCart' of undefined
After spending few hours in internet and following some tutorials I did following changes to the code and then it started working.
But still I dont understand what i have done here
var cart = (function (cart) {
cart.createCart = function (cartId) {
console.log(cartId);
cartId = document.getElementById(cartId);
}
return cart;
}(cart || {}));
var shoopingCart = cart.createCart("MyCart");
Can some one please explain me why the code started to work after passing cart || {} expression into the anonymous function? Some detailed explanation would be great. :)
cartas a parameter, without passingcart || {}you are passing in nothing, socartwill be undefined. remember that IIFE have a completely isolated scope