-
建议3:减少全局变量污染
1.把多个全局变量都追加在一个名称空间下,将显著降低与其他应用程序产生冲突的概率,应用程序也会变得更容易阅读。
var My = {}; My.name = { "first-name":"first", "last-name":"last" }; My.work = { number:123, one:{ name:"one", time:"2017-3-11", city:"南京" }, two:{ name:"two", time:"2017-3-12", city:"苏州" } };
2.使用闭包体将信息隐藏
var foo = function(){ var a = 1, b = 2; var bar = function(){ var b = 3, c = 4; a += b+c; }; bar(); };
-
建议4:注意JavaScript数据类型的特殊性
1.防止浮点数溢出
num = 0.1+0.2;//0.30000000000000004
a = (1+2)/10;//0.3
2.正确检测数据类型
//安全检测JavaScript基本数据类型和内置对象 //参数:o表示检测的值 /*返回值:返回字符串"undefined","number","boolean","string","function","regexp","array","date","error"*/ function typeOf(o){ var toString = Object.prototype.toString; //获取对象的toString()方法引用 //列举基本数据类型和内置对象类型,可以进一步补充该数组的检测数据类型范围 var type = { "undefined":"undefined", "number":"number", "boolean":"boolean", "string":"string", "[object Function]":"function", "[object RegExp]":"regexp", "[object Array]":"array", "[object Date]":"date", "[object Error]":"error" }; return type[typeof o]|| type[ toString.call(o)]||(o?"object":"null"); }