首页 > 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学习者快速成长!