动漫引擎

导航

JavaScript Best Practices (w3cschool)

 

JavaScript Best Practices (w3cschool)

Local Variables:

·      总是在前面集中定义变量,(包括 for 的i).(strict mode)

·      并且赋值, 避免 undefined的变量

·      视numbers, strings, or booleans 为基本元素, 不要当做objects. 因为obj会引来大开销

 var x = "John";       (不要用:      var y = new String("John");)

 

·      赋值用literal或者确定的值,不要用new和object, 例如:

·       Use {} instead of new Object()

·       Use "" instead of new String()

·       Use 0 instead of new Number()

·       Use false instead of new Boolean()

·       Use [] instead of new Array()

·       Use /()/ instead of new RegExp()

·       Use function (){} instead of new Function()

表达式

·      Switches: 必须要有 Defaults

·      用Assert断言非法的值

·      用 红字显示错误

·      彻底用===代替==

·      避免使用eval()

·      少用: 全局的变量/函数


函数:

·      一定要检查形参是否undefined, 并且付初始值。

·      用function语法定义函数, 不用var语法

类:

·      Public函数列在最前边,(按照abc顺序排列)

·      函数定义写在后边

·      用vm代替this,避免歧义


注意自动的类型转换

var x = 5 + "7";     // x.valueOf() is 57,  typeof x is a string

var x = "5" + 7;     // x.valueOf() is 57,  typeof x is a string

 

var x = 5 - "7";     // x.valueOf() is -2,  typeof x is a number

var x = "5" - 7;     // x.valueOf() is -2,  typeof x is a number

 

var x = 5 - "x";     // x.valueOf() is NaN, typeof x is a number

posted on 2017-03-10 08:23  动漫引擎  阅读(133)  评论(0编辑  收藏  举报