<h1>代码重构</h1>
<h1>1.提炼函数:在JavaScript开发中,我们大部分时间都与函数打交道,所以我们希望这些函数有着良好的命名,函数的逻辑清晰明了。</h1>
<p>如果一个函数过长,不得不加上若干注释才能让这个函数显得易读一些,那么这个函数就很有必要进行重构。</p>
<p>如果在函数中有一段代码可以被独立出来,那我们最好把这些代码放进另外一个独立的函数中。这是一种常见的优化工作,这样做的好处主要有以下几个好处:</p>
<p>避免出现超大函数;<p>
<p>独立出来的函数有助于代码的复用;</p>
<p>独立出来的函数更容易被复写;</p>
<p>独立出来的函数如果有一个良好的命名,它本身就起到了注释的作用。</p>
<script>
//示例负责取到用户信息的函数
var getUserInfo = function(){
Ajax( "http:xxx", function(data){
printDetails( data );
} );
};
var printDetails = function( data ){
console.log( data.userId );
console.log( data.userName );
console.log( data.nickName );
}
</script>
<h1>2.合并重复的代码</h1>
<h1>3.把条件分支语句提炼成函数</h1>
<script>
var isSummer = function(){
var date = new Date();
return date.getMonth() >= 6 && date.getMonth() <= 9;
};
var getPrice = function( price ){
if( isSummer() ){ //夏天
return price * 8;
};
return price;
};
</script>
<h1>4.合理使用循环</h1>
<h1>5.提前让函数退出嵌套循环</h1>
<h1>6.传递对象参数代替过长的参数列表</h1>
<h1>7.尽量减少参数数量</h1>
<h1>8.合理使用链式调用</h1>
<h1>9.分解大型类</h1>
<script>
//“街头霸王”游戏示例
var Attack = function( role ){
this.role = role;
};
Attack.prototype.start = function( type ){
return this.list[ type ].call( this );
};
Attack.prototype.list = {
waveBoxing: function(){
console.log( this.role.name + ":使用波动拳" );
},
whirlKick: function(){
console.log( this.role.name + "使用旋风腿" );
}
};
var Role = function( name ){
this.name = name;
this.attackObj = new Attack( this );
};
Role.prototype.attack = function( type ){
this.attackObj.start( type );
};
var role = new Role( "谢夏岭" );
role.attack( "waveBoxing" );
role.attack( "whirlKick" );
</script>
<h1>10.用return退出多重循环</h1>
js代码重构
最新推荐文章于 2024-07-21 14:17:52 发布