// 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.
Disadv:
Selain modul & corak modul ES6 asli, JS juga menyokong sistem modul lain yang bukan asli JS. Cth. AMD, CommmonJS
Cth. Modul CommonJS digunakan dalam Node.js untuk semua kewujudannya. Baru-baru ini modul ES6 telah dilaksanakan dalam Node.js
Semua modul pada repositori npm masih menggunakan sistem modul commonJS kerana npm pada asalnya bertujuan untuk nod. Hanya kemudian, npm menjadi repositori untuk seluruh dunia JS. Oleh itu, kami pada asasnya terperangkap dengan CommonJS. Jadi, CommonJS masih perlu diberi perhatian kerana kesannya dalam Node.js
Sama seperti modul ES6, 1 fail ialah 1 modul dalam CommonJS.
Kod commonJS tidak akan berfungsi dalam penyemak imbas, tetapi ia akan berfungsi dalam node.js
Modul ES akan menggantikan semua sistem modul akhirnya tetapi pada masa ini kita perlu menggunakan commonjs juga.
kata kunci eksport ialah objek, yang tidak ditakrifkan dalam kod kami serta dalam penyemak imbas.
// 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')
Atas ialah kandungan terperinci Modul. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!