
书写可维护的代码
代码的维护,修改以及扩展都是需要时间和人力成本的,所以为了减少浪费不必要的成本,从一开始就要书写可维护的代码,这样给自己也给项目其他人提供便利。
书写可维护的代码意味着你的代码是:
- 可读的
- 一致性
- 可预测的
- 可维护以及可扩展的
全局变量
全局变量的定义:
1.var + 变量名 在function外声明。即为全局变量。
<script>
var global = 'test';
function getGlobalValue () {
console.log(global)
}
getGlobalValue() // 'test'
</script>
2.不使用var,隐式声明全局变量
<script>
global = 'test';
function getGlobalValue () {
global_1 = 'test1';
console.log(global);
}
getGlobalValue(); //'test'
console.log(global_1); // 'test1'
</script>
3.使用window全局来声明
<script>
window.global = 'test';
console.log(global)
</script>
应尽量避免使用全局变量。过度使用全局变量会导致一些问题:
1.全局变量保存在静态存贮区。与局部变量的动态分配,动态释放内存相比,生存期较长,会占用比较多的内存单元。
2.全局变量破坏了函数的封装性能。
3.全局变量使函数的代码可读性降低。由于多个函数都可能使用全局变量,函数执行时全局变量的值可能随时发生变化,对于程序的查错和调试都非常不利。
for-in循环(for-in Loops)
for-in循环主要用在非数组对象的遍历上。同时也会遍历从原型链上下来的方法,使用hasOwnProperty()
方法,可以过滤掉从原型链上下来的方法。
var student = {
name : 'xiaoming',
age : 18,
sex : 'man'
} //给所有对象添加一个方法
if (typeof Object.prototype.clone === "undefined") {
Object.prototype.clone = function () {};
} //遍历对象属性,没有过滤原型方法
for (var item in student){
console.log(item + ':' + student[item])
}
/*result:
name:xiaoming
age:18
sex:man
clone:function () {}
*/ //使用hasOwnProperty()过滤原型方法
for (var item in student){
if(student.hasOwnProperty(item)){
console.log(item + ':' + student[item])
}
} //另一种方法
var item , hasOwn = Object.prototype.hasOwnProperty;
for(item in student){
if(hasOwn.call(student, item)){
console.log(item + ':' + student[item])
}
}
/*result:
name:xiaoming
age:18
sex:man
*/
其他规范
其他规范包括空格,缩进,循环花括号,函数命名,以及注释等,也要形成统一的规范。方便代码的阅读以及多人协作。