// 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、CommmonJS
元。 CommonJS モジュールは、Node.js の存在全体にわたって使用されます。最近、ES6 モジュールが Node.js
に実装されました。
npm は元々ノード用に意図されていたため、npm リポジトリ上のすべてのモジュールは依然として commonJS モジュール システムを使用します。その後になってようやく、npm が JS 世界全体のリポジトリになりました。したがって、基本的に CommonJS を使い続けることになります。そのため、Node.js
における CommonJS の影響に依然として注意を払う必要があります。
ES6 モジュールと同様に、CommonJS では 1 ファイルが 1 モジュールになります。
commonJS コードはブラウザでは動作しませんが、node.js
では動作します。
ES モジュールは最終的にはすべてのモジュール システムを置き換えますが、現時点では commonjs も使用する必要があります。
export キーワードはオブジェクトですが、コードにもブラウザにも定義されていません。
// 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