switch 模式
每个 case 和 switch 对齐(这里不考虑花括号相关的缩进规则) 每个 case 中的代码整齐缩进 每个 case 都以 break 作为结束 避免连续执行多个 case 语句块(当省略 break 时会发生),如果你坚持认为连续 执行多 case 语句块是最好的方法,请务必补充文档说明,对于其他人来说,这种情况看起来是错误的。 以 default 结束整个 switch, 以确保即便是在找不到匹配项时也会有正常的结果 避免隐式类型转换(推荐使用===和!===) typeof null==='object';instanceof 检测引用值 避免使用 eval()(用 new Function()来代替,它是局部函数作用域,var 定义的变量不会自动变成全局变量) 使用 parseInt()进行数字转换,总是指定第二个参数(parseInt(year, 10)) 编码风格(缩进,花括号,左花括号位置,空格) 命名规范(构造函数大驼峰 函数和方法小驼峰 变量名小写下划线分隔 常量全大写) 注释jsdoc生成文档,eslint检查,相互评审1.对象直接量,JSON,正则表达式直接量
1.强制new,避免使用其他的内置构造函数:String()、Number()、Boolean()以及不同种类的
Error()构造器,that=this
命名空间方式
优点:
- 避免了自身代码的命名冲突, - 避免了同一个页面上自身代码和第三方代码的冲突
缺点
- 代码量稍有增加;在每个函数和变量前加上这个命名空间对象的前缀,会增加代码量,增大文件大小 - 该全局实例可以被随时修改 - 命名的深度嵌套会减慢属性值的查询
模块模式(命名空间模式+IIFE+私有和特权成员模式+依赖声明模式)
MYAPP.utilities.module = (function (app, global) { return (function(){})() }(MYAPP, this))
沙箱模式
Sandbox.modules = {}; Sandbox.modules.dom = function (box) {}; Sandbox('dom', 'event', function (box) { Sandbox('ajax', function(box) { }); });
链式调用模式
优点:节省代码量,易读性缺点:调用这样写的代码会更困难
myobj.method1("hello").method2().method3("world").method4();
代码复用模式
类式继承1:默认模式
缺点:既继承了(父对象)“自己的属性”,也继承了原型中的属性。大部分情况下你可能并不需要“自己的属性”,因为它们更可能是为实例对象添加的,并不用于复用。
function inherit(C, P) { C.prototype = new P(); }
类式继承2:借用构造函数
缺点:无法继承原型
function Child(a, c, b, d) { Parent.apply(this, arguments); }
类式继承3:借用并设置原型(1,2的缺点修复,接近java)
缺点:父构造函数被调用了两次,所以不是很高效
function Child(a, c, b, d) { Parent.apply(this, arguments); } Child.prototype = new Parent();
类式继承4:共享原型
缺点:修改原型影响所有的继承
function inherit(C, P) { C.prototype = P.prototype; }
类式继承5:临时构造函数
function inherit(C, P) { var F = function () {}; F.prototype = P.prototype; C.prototype = new F(); }
原型继承(现代继承模式)
var child = Object.create(parent);
借用方法
//call() example notmyobj.doStuff.call(myobj, param1, p2, p3); // apply() example notmyobj.doStuff.apply(myobj, [param1, p2, p3]);
var obj = { myprop: 'my value' };
var corolla = CarMaker.factory('Compact'); var solstice = CarMaker.factory('Convertible'); var cherokee = CarMaker.factory('SUV'); corolla.drive(); // "Vroom, I have 4 doors" solstice.drive(); // "Vroom, I have 2 doors" cherokee.drive(); // "Vroom, I have 17 doors"
var element; while (element = agg.next()) { // do something with the element ... console.log(element); }
var sale = new Sale(100); // the price is 100 dollars sale = sale.decorate('fedtax'); // add federal tax sale = sale.decorate('cdn'); // format using CDN sale.getPrice(); // "CDN$ 105.00"
var data = { first_name: "Super", last_name: "Man", age: "unknown", username: "o_O" }; validator.config = { first_name: 'isNonEmpty', age: 'isNumber', username: 'isAlphaNum' }; validator.validate(data); if (validator.hasErrors()) { console.log(validator.messages.join("\n")); }
var myevent = { // ... stop: function (e) { // others if (typeof e.preventDefault === "function") e.preventDefault(); if (typeof e.stopPropagation === "function") e.stopPropagation(); // IE if (typeof e.returnValue === "boolean") e.returnValue = false; if (typeof e.cancelBubble === "boolean") e.cancelBubble = true; } // ... };
scroll_per_second=throttle(scroll,1000)
counter=function(){ var i=0; return function(){ return ++i; } } counter()
paper.subscribe(joe.drinkCoffee); paper.subscribe(joe.sundayPreNap, 'monthly'); paper.daily(); paper.monthly();
减少DOM访问操作次数
避免在环境中访问 DOM 将 DOM 引用赋给本地变量,然后操作本地变量 当可能的时候使用 selectors API 遍历 HTML collections 时缓存 length事件处理:隔离应用逻辑,不要分发event对象
var MyApplication={ handleClick(event){ this.showPopup(event.clientX,event.clientY) }, showPopup:function(x,y){ } } b.addEventListener('click', function(event){ MyApplication.handleClick(event) }, false);
事件委托
Y.delegate('click', myHandler, "#click-wrap", "button");
加载策略
script 元素放到页面的尾部 HTTP 分块 动态<script>元素 延迟加载 按需加载 预加载 JavaScript UI松耦合 浏览器嗅探:特性判断《Javascript设计模式》
《编写可维护的Javascript》
https://github.com/tcorral/De...