js代码重构

      <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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值