„Wenn ein Arbeiter seine Arbeit gut machen will, muss er zuerst seine Werkzeuge schärfen.“ – Konfuzius, „Die Gespräche des Konfuzius. Lu Linggong“
Titelseite > Programmierung > Module

Module

Veröffentlicht am 04.11.2024
Durchsuche:372

Modules

  • Modulmuster wurde vor ES6-Modulen verwendet.
  • Ziel: Funktionalität kapseln, private Daten unterstützen, öffentliche API verfügbar machen und all dies wird durch die Verwendung von IIFEs erreicht.

IIFE: Ex. (Funktion(){})();

// 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.

Das Modulmuster funktionierte bereits vor ES6-Modulen.

Nachteil:

  1. Wenn wir nun ein Modul pro Datei möchten, wie wir es bei ES6-Modulen getan haben, müssen mehrere Skripte erstellt und innerhalb der HTML-Datei verknüpft werden.
  2. Auch die Reihenfolge, in der das Skript geladen wird, spielt eine Rolle.
  3. Alle diese Variablen werden im globalen Bereich leben.

Neben nativen ES6-Modulen und Modulmustern unterstützte JS auch andere Modulsysteme, die nicht für JS nativ waren. Ex. AMD, CommmonJS
Ex. CommonJS-Module werden in Node.js während ihrer gesamten Existenz verwendet. Kürzlich wurden ES6-Module in Node.js implementiert
Alle Module im NPM-Repository verwenden weiterhin das CommonJS-Modulsystem, da NPM ursprünglich für Node gedacht war. Erst später wurde npm zum Repository für die gesamte JS-Welt. Daher bleiben wir im Grunde bei CommonJS hängen. Daher muss CommonJS weiterhin als seine Bedeutung in Node.js beachtet werden
Genau wie beim ES6-Modul ist 1 Datei 1 Modul in CommonJS.
Der commonJS-Code funktioniert nicht im Browser, aber in node.js
ES-Module werden irgendwann alle Modulsysteme ersetzen, aber ab sofort müssen wir auch CommonJS verwenden.

export Schlüsselwort ist ein Objekt, das weder in unserem Code noch im Browser definiert ist.

// 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')
Freigabeerklärung Dieser Artikel ist abgedruckt unter: https://dev.to/mahf001/iife-module-pattern-commonjs-5gkd?1 Bei Verstößen wenden Sie sich bitte an [email protected], um ihn zu löschen
Neuestes Tutorial Mehr>

Haftungsausschluss: Alle bereitgestellten Ressourcen stammen teilweise aus dem Internet. Wenn eine Verletzung Ihres Urheberrechts oder anderer Rechte und Interessen vorliegt, erläutern Sie bitte die detaillierten Gründe und legen Sie einen Nachweis des Urheberrechts oder Ihrer Rechte und Interessen vor und senden Sie ihn dann an die E-Mail-Adresse: [email protected] Wir werden die Angelegenheit so schnell wie möglich für Sie erledigen.

Copyright© 2022 湘ICP备2022001581号-3