모듈

王林
풀어 주다: 2024-09-04 20:30:10
원래의
471명이 탐색했습니다.

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. 해당 변수는 모두 전역 범위에 존재합니다.

JS는 기본 ES6 모듈 및 모듈 패턴 외에도 JS에 기본이 아닌 다른 모듈 시스템도 지원했습니다. 전. AMD, 커먼JS
전. CommonJS 모듈은 Node.js의 모든 존재에 사용됩니다. 최근 ES6 모듈이 Node.js에 구현되었습니다
npm 저장소의 모든 모듈은 npm이 원래 node.js용으로 의도되었기 때문에 여전히 commonJS 모듈 시스템을 사용합니다. 나중에야 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')
로그인 후 복사

위 내용은 모듈의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!