何为模式
模式 就是经验,解决某个问题(完成某个任务)的多个选项中,最佳实践
什么问题,什么任务
大程序分而治之的问题和任务 问题:大部分程序(计算功能)的分割 任务:横向(专业)纵向(通用)分割 独立专业的程序功能:模块封装 通用的共享程序功能:类继承
具体分割例子
根据分割的需求,JS模块有不同的形态特征,例如有传入依赖参数(window),有返回公开接口;有只执行一次(单个实例),或多个实例 所以,模块有调用和被调用的,有逻辑公共和特特殊的,等属性
模块模式
模块模式,让JS拥有“类封装”encapsulation JS的对象(函数)只有打包功能,没有 private性 The module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.
JS模块与JS类
JS 没有类,但任何对象(object)都会有一个父原型,可以对象进行「继承」扩展,所以JS对象可直接看“类”,至少是一种特例 因为JS内置支持对象和对象原型继承,所以 JS本质是OO的,只是类封装需要模块模式来模拟,才比较完整的实现OO构造术 JS模块不等于JS类,因为一个模块可以“装”多个类定义,所以是更高一级有代码管理单元
JS模块 是比较 JS类对象 更高的代码管理工具
JS模块通过函数对象(函数表达式,轻便对象)技术实现的 JS模块 实际上是 JS对象 的一种特殊使用 JS函数对象可接受参数,可返回值,这些都决定JS模块的使用意义
没有模块,“大程序”容易产生名字冲突
名字冲突是任务的表象 In JavaScript, the module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of your function names conflicting with other func- tions defined in additional scripts on the page. 模块模式最初定义为为传统软件工程中的类提供私有和公共封装的一种方式。
在 JavaScript 中,模块模式用于进一步模拟类的概念,以便我们能够在单个对象中同时包含公共/私有方法和变量,从而保护特定部分免受全局作用域的影响。这导致函数名称与页面上其他脚本中定义的其他函数冲突的可能性降低。
为什么
对计算功能的私有封装,是分割大程序(功能)的最基础技术,另一项技术是是类继承
私有封装
大计算功能,由一个或以上的粒度较小(但独立)计算功能,以某种方式复合而成
计算功能的分割与复合
如何做到的
JS嵌套函数的 闭包 为基础技术 The module pattern encapsulates 'privacy', state and organization using closures. It provides a way of wrapping a mix of public and private methods and variables, pro- tecting pieces from leaking into the global scope and accidentally colliding with another developer's interface. With this pattern, only a public API is returned, keeping every- thing else within the closure private.
Within the module pattern, variables or methods declared are only available inside the module itself thanks to closure. --- This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We’ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application. 这是使得模块化编程成为可能的基础结构,而且实在是Js最好的一个特性。我们所做的仅仅是创建一个匿名函数,然后立即去执行它。在匿名函数内部的所有代码都运行在一个闭包中,闭包在我们的应用运行的整个生命周期内提供了隐蔽和状态。
(function () { // ... all vars and functions are in this scope only // still maintains access to all globals }());