JavaScript-StepPitGuide
  • 封面
  • 前言
  • 基础知识
    • 基础知识
      • 变量声明
      • 变量类型和计算
      • 作用域
      • 基本数据类型
        • Undefined
        • Null
        • Boolean
        • Number
        • String
        • Symbol
      • 类型转换
    • 引用类型
      • Object类型
      • Array类型
        • 检测数组
        • 转换方法
        • 栈方法
        • 队列方法
        • 重排序方法
        • 操作方法
        • 位置方法
        • 迭代方法
        • 归并方法
      • Date类型
      • RexExp类型
      • Function类型
      • Set类型(ES6)
      • Map类型(ES6)
    • BOM
      • window对象
      • location对象
      • navigator对象
      • screen对象
      • history对象
    • DOM
      • DOM节点操作
      • DOM结构操作
    • 事件
      • 事件流
      • 事件注册与触发
      • 事件对象
      • 事件分类
    • 异步
      • Ajax
      • Promise
    • 正则表达式
    • 面向对象程序设计
      • 构造函数
      • 原型链
      • 继承
      • New
      • Object.create
    • 函数表达式与函数式编程
      • 递归
      • 闭包
      • this
      • 箭头函数
      • 高阶函数
      • 由函数构建函数
      • 纯度、不变性和更改政策
      • 基于流的编程
      • 无类编程
      • 函数基本应用
    • 语法规则
      • ESlint
  • 进阶知识
    • 算法应用
      • 基本排序算法
        • 冒泡排序
        • 选择排序
        • 插入排序
        • 希尔排序
        • 归并排序
        • 快速排序
    • 模块化
      • AMD
      • CommonJS
      • ES6模块化
    • 应用
      • Socket.io库
      • async+await异步调用
      • axios
    • 设计模式
    • 性能优化
    • 工具
      • 时间操作
    • 异常监控
    • 安全🔐
      • XSS
      • CSRF
    • 跨域
      • 跨域
      • 跨域方法
        • Hash
        • JSONP
        • CORS
        • XDomainRequest
由 GitBook 提供支持
在本页
  • 模块化
  • 不使用模块化
  • 使用模块化

这有帮助吗?

  1. 进阶知识

模块化

模块化

  • 不使用模块化

  • 使用模块化

  • AMD

  • CommonJS

  • ES6

不使用模块化

  • util getFormatDate函数

  • a-util.js aGetFormatDate函数 使用getFormatDate

  • a.js aGetFormatDate

  • 定义

//util.js
function getFormatDate(date,type) {
  //type === 1返回 2017-06-15
  //type === 2返回 2017年6月15日 格式
  //...
}
//a-util.js
function aGetFormatDate(data) {
  //返回
  return getFormatDate(date,2);
}
// a.js
var dt = new Date()
console.log(aGetFormatDate(dt));
  • 使用

<script src="util.js"></script>
<script src="a-util.js"></script>
<script src="a.js"></script>
<!-- 1.这些代码中的函数必须是全局变量,才能暴露给使用方。全局变量污染 -->
<!-- 2. a.js 知道要引用 a-util.js ,但是他知道还需要依赖于util.js吗? -->

使用模块化

//util.js
export{
  getFormatDate:function (data,type) {
    //type === 1 返回 2017-06-15
    //type === 2 返回 2017年6月15日 格式
  }
}
//a-util.js
var getFormatDate = require('util.js');
export{
  aGetFormatDate:function (date) {
    //要求返回 2017年6月15日 格式
    return getFormatDate(date,2);
  }
}
// a.js
var aGetFormatDate = require('a-util.js')
var dt = new Date();
console.log(aGetFormatDate(dt));

//直接‘<script src="a.js"></script>’,其他的根据依赖关系自动引用
//那两个函数,没必要做成全局变量,不会带来污染和覆盖
上一页快速排序下一页AMD

最后更新于4年前

这有帮助吗?