建设银行住房公积金预约网站,wordpress 视频主题,创建自己的个人网站,做视频网站流量费高吗模块化的作用主要体现在封装和隐藏私有实现细节#xff0c;以及保证全局命名空间清洁上#xff0c;因而模块之间不会意外修改各自定义的变量、函数和类。 
1 模块 
1.1 代码打包工具基本工作原理 
在函数中声明的局部变量和嵌套函数都是函数私有的。这意味着我们可以使用立即… 模块化的作用主要体现在封装和隐藏私有实现细节以及保证全局命名空间清洁上因而模块之间不会意外修改各自定义的变量、函数和类。 
1 模块 
1.1 代码打包工具基本工作原理 
在函数中声明的局部变量和嵌套函数都是函数私有的。这意味着我们可以使用立即调用的函数表达式来实现某种模块化把实现细节和辅助函数隐藏在包装函数中只将模块的公共API作为函数的值返回。 
const moduleExport  (function () {     function sayHello() {         console.log(hello moduleExport)     }     function sum(a,b) {         console.log(a    b    (a  b))     }     return { sayHello, sum } }()); moduleExport.sayHello(); // hello moduleExport moduleExport.sum(5,8); // 5813 
打包工具把每个文件的内容包装在一个立即调用的函数表达式中还可以跟踪每个函数的返回值并将所有内容拼接为一个大文件 
const modules  {}; function requireCustom(moduleName) { return modules[moduleName] } modules[student.js]  (function () {    const exports  {};    // student.js 内容     function study() {         console.log(好好学习天天向上);     }     // student.js 内容截止     exports.study  study;    return exports; }()); modules[teacher.js]  (function () {   const exports  {};   function teach() {       console.log(教授英语);   }   function test() {       console.log(今天考试);   }   exports.teach  teach;   exports.test  test;   return exports; }()); const student  requireCustom(student.js); student.study(); // 好好学习天天向上 const teacher  requireCustom(teacher.js); teacher.teach(); // 教授英语 teacher.test(); // 今天考试 
以上代码展示了浏览器代码打包工具(webpack)的基本原理也是对Node程序中使用的require()函数的一个简单介绍。 
1.2 Node中的模块 
在Node模块中每个文件都是一个拥有私有命名空间的独立模块。在一个文件中定义的常量、变量、函数和类对该文件而言都是私有的除非该文件会导出它们。而模块导出值只有被另一个模块显式导入后才会在该模块中可见。 
Node使用require()函数导入其他模块通过设置Exports对象属性或完全替换module.exports对象来导出公共API。 
function product() {     console.log(生产商品); } function design() {     console.log(设计商品); } module.exports  { product, design }; 
factory.js 
module.exports  function () {     console.log(消费商品) }; 
customer.js 
const factory  require(./factory); const customer  require(./customer); factory.design(); // 设计商品 factory.product(); // 生产商品 customer(); // 消费商品 
shop.js 
1.3 ES6中的模块 
ES6模块化与Node的模块化在概念上是相同的。与Node模块的区别在于导入和导出所用的语法以及浏览器中定义模块的方式。 
要从ES6模块导出只要在声明前加上export关键字即可。导入其他模块要使用import关键字。 
function work() {     console.log(努力工作); } function fished() {     console.log(偶尔摸鱼); } export { work, fished } 
employee.js 
export default function () {     console.log(发薪水); } 
boss.js 
export { work, fished  } from ./employee.js; export { default as payByBoss } from ./boss.js; console.log(import.meta.url); // http://localhost:63342/js-study/day2/company.js 
company.js 
!DOCTYPE html html langen head     meta charsetUTF-8     title公司/title /head body script typemodule     import { work, fished, payByBoss }  from ./company.js;     work(); // 努力工作     fished(); // 偶尔摸鱼     payByBoss(); // 发薪水 /script /body /html 
company.html