Modular Programming with JavaScript
目录
- 1 为什么模块化
- 2 JavaScript重要的OOP概念
- 3 模块设计模式
- 4 设计简单的模块
- 5 模块增强
- 6 克隆、继承和子模块
- 7 Base、Sandbox and Core
- 8 应用实现:Put it all together
- 9 模块化应用设计与测试
- 10 企业级模块化设计、AMD、CommonJS与ES6模块
为什么模块化
JavaScript重要的OOP概念
- 单例对象:var MyObj = {};
- this
- 函数内的this:
- f()作为函数直接调用:this引用外部的window(但是嵌套作用域的情况下呢?)
- new f():创建了一个新的context
- 对象常量内的this:引用自身
- 但是如果(MyObj.f=MyObj.f)(),则this又变成引用window了
- 如果MyObj.f内部返回一个闭包,则闭包内的this引用window *
- 要让这个闭包引用MyObj实例,需要先在外部var that=this;
- 函数内的this:
- Closures
- Encapsulation and scoping
- function内部的var相当于private变量。also, "函数作用域"
- IIFE可以在function内部创建一个新的private作用域,其中定义的var外部不可访问
- Inheritance
- JavaScript只支持实现继承(vs 接口继承)
- Prototype chaining
- ChildType.prototype = new BaseType();
- ?最佳实践:ChildType.prototype.constructor = ChildType;
- Constructor stealing
- function ChildType(){ BaseType.call(this); } //缺点:BaseType.prototype上定义的属性没有被ChildType实例共享
- Parasitic combination inheritance
- 前2者的组合:BaseType.call(this); 及 ChildType.prototype = BaseType.prototype; 之后定义ChildType自己的方法...
- Constructor property
- ChildType.prototype.constructor = ChildType;
- Native support for inheritance
- ES5原型继承:Object.create()
模块设计模式
- 匿名函数内部返回匿名对象:
- var MySingletonObject = function(){ var ....; return { getName: function(){...}
- var MySingletonObject = function(){ var ....; return { getName: function(){...}
- 对象工厂(最佳实践?)
- Creating loose coupling among modules
- ApplicationInitModule(作者自己编写的一个类,负责管理模块的注册和初始化)
设计简单的模块
- SPA
- MV*
- Application controller
- 职责:视图更新(PageUpdater)、客户端存储、通信、消息、Log
- Application view
- 我还以为这里作者会讲解一个最简单的React呢,算了
模块增强
克隆、继承和子模块
- constructor函数,prototype
- Shallow cloning与Deep cloning
- jQuery.extend
- lodash:var deep = _.cloneDeep(objects);
- var cloneObj = (JSON.parse(JSON.stringify(originalObj)));
- 定制clone://primitive对象直接赋值就好了
- var newClonedObj = new this.constructor();
- Module inheritance using __proto__ object
- 这与函数对象的prototype属性有什么区别?
- Submodules
Base、Sandbox and Core
- Base:aware并适配第3方框架(jQuery, Dojo, lodash, ...)
- Sandbox
- Isolating the sandbox instances from each other
- ... sandBox.contextObj.handelFavLinkClick(e.target);
- Core:实现业务逻辑,MV*,logging,...
- Providing plug-and-play capability
- 使用localStorage作为cache
- mainCore.jQuery = $ = ImagesInc_Base.getBaseModule(); //从全局导入到模块内部?
- Providing plug-and-play capability
应用实现:Put it all together
- 存储component's object definition描述到localStorage???
- Publish-subscribe implementation in MainCore
- sandBox.publishCustomEvent?
模块化应用设计与测试
企业级模块化设计、AMD、CommonJS与ES6模块
- AMD:
- define('moduleOneId', ['dependency'], function(dependency) { return { ...
- define('moduleOneId', ['dependency'], function(dependency) { return { ...
- CommonJS
- exports.someFunc = function(){ ...
- ES6 module
- export function sayHello(name) { ... }
- function sayBye(name) { ... }
- export sayBye;
这本书内容有点矬,很多地方非常空洞,与核心概念“JS模块化编程”并不搭界。