// IIFE Goal: Create a new scope, return the data just once. All of data inside IIFE will be private as it would inside the fn scope. // Using this way, we don't need to call it separately. And it ensures its called only once. // IIFE is created only once, goal is 'NOT TO REUSE' by executing it multiple times. // Result of running an IIFE is stored, or else it will disappear simply. const ShoppingCart2 = (function(){ const cart = []; const shippingCost = 10; const totalPrice = 237; const totalQuantity = 10; const addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ${product} added to cart. Shipping cost is ${shippingCost}`); }; const orderStock = function(product, quantity){ console.log(`${quantity} ${product} ordered from supplier`); }; // Need to return something, in order to return a public API. For that, an object is returned containing stuff which needs to be made public. return { addToCart, cart, totalPrice, totalQuantity }; })(); // Everything inside the above module is private to the module. // The above fn returns the object mentioned inside return statement and assign it to the ShoppingCart2 variable mentioned at the start of fn. This IIFE is returned then long ago. // All this is possible because of closures. Hence, addToCart can acccess the cart variable. ShoppingCart2.addToCart('apple', 4); ShoppingCart2.addToCart('pizza', 5); ShoppingCart2; ShoppingCart2.shippingCost; // inaccessible.
Отказ:
Помимо собственных модулей и шаблонов модулей ES6, JS также поддерживает другие системы модулей, которые не являются собственными для JS. Бывший. AMD, CommonJS
Бывший. Модули CommonJS используются в Node.js на протяжении всего его существования. Недавно модули ES6 были реализованы в Node.js
Все модули в репозитории npm по-прежнему используют систему модулей commonJS, поскольку npm изначально предназначался для node. Лишь позже npm стал репозиторием для всего мира JS. Следовательно, мы по сути застряли на CommonJS. Таким образом, на CommonJS по-прежнему необходимо обращать внимание, поскольку он используется в Node.js
Как и в случае с модулем ES6, в CommonJS 1 файл — это 1 модуль.
Код commonJS не будет работать в браузере, но будет работать в node.js
Модули ES в конечном итоге заменят всю систему модулей, но на данный момент нам также нужно использовать commonjs.
Ключевое слово экспорта — это объект, который не определен ни в нашем коде, ни в браузере.
// EXPORT export.addToCart = function(product, quantity){ cart.push({product, quantity}); console.log(`${quantity} ${product} added to cart. Shipping cost is ${shippingCost}`); }; // IMPORT: is similar to ES Modules but would use a require fn. // require is not defined in browser env but its defined in node env as its a part of commonjs const addToCart = require('./shoppingCart.js')
Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3