[Javascript] Module Pattern

Module pattern provide a way to have both public and private pieces with the export keyword. This protects values from leaking into the global scope or ending up in a naming collision.

secretis a private variable inside Math.js which is not accessible outside the file.

 

How to use module partten in Javascript env?

HTML:

If doing like this:

<script src="math.js"></script>

All the math.js variable will be global.

Doing this:

<script src="index.js" type="module" defer></script>

Apply modular pattern.

 

Node.js

If you want to use "import & export", you have to add "type": "module",to package.json.

  

posted @ 2022-08-26 15:18  Zhentiw  阅读(32)  评论(0编辑  收藏  举报