首頁 > web前端 > js教程 > 主體

模組

王林
發布: 2024-09-04 20:30:10
原創
486 人瀏覽過

Modules

  • 模組模式在 ES6 模組之前使用。
  • 目標:封裝功能、支援私人資料、公開公開 API,所有這些都是透過使用 IIFE 來實現的。

IIFE:例如。 (功能(){})();

// 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 模組之前就已經起作用了。

缺點:

  1. 現在,如果我們想要每個檔案一個模組,就像我們使用 ES6 模組一樣,那麼需要建立多個腳本並在 HTML 檔案中連結。
  2. 腳本載入的順序也很重要。
  3. 所有這些變數都將存在於全域範圍內。

除了原生的 ES6 模組和模組模式之外,JS 還支援其他非 JS 原生的模組系統。前任。 AMD、CommonJS
前任。 Node.js 中自始至終都使用 CommonJS 模組。最近 ES6 模組已經在 Node.js 中實作
npm 儲存庫上的所有模組仍然使用 commonJS 模組系統,因為 npm 最初是為 Node 設計的。直到後來,npm 才成為整個 JS 世界的儲存庫。因此,我們基本上只能使用 CommonJS。所以,CommonJS 在 Node.js 中的影響還是需要被注意
就像 ES6 模組一樣,CommonJS 中 1 個檔案就是 1 個模組。
commonJS 程式碼在瀏覽器中不起作用,但在 Node.js 中可以
ES Modules 最終將取代所有模組系統,但目前我們還需要使用 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')
登入後複製

以上是模組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!