JavaScript 模拟重载

 

 

/**
  * 参数个数对应 各自处理的函数 不指定 则执行 默认函数
  * [
  *    d       : function (             ) {}
  *  , 0       : function (             ) {}
  *  , 1       : function ( a           ) {}
  *  , 2       : function ( a, b        ) {}
  *  , 3       : function ( a, b , c    ) {}
  *  , 4       : function ( a, b , c, d ) {}
  * ]
 */

! function ()
  {
    var
      _reload = ( function ()
      {
        var
          _default = function () {}             //  设置默认函数

          ; return function ( funcs, _def )
            {
              ; funcs       = funcs.slice()     //  配置处理函数 slice 防外部修改
              ; funcs["d"]  = _def || _default  //  配置默认函数

              ; return function ()
                {
                  ; return ( funcs[ arguments.length ] || funcs.d ).apply( this, arguments )
                }
            }
      })()

    , test    = _reload(
      [
          function (         ) { return 0           }
        , function ( x       ) { return x * x       }
        , function ( x, y    ) { return x / y       }
        , function ( x, y, z ) { return x * y * z   }
      ] , function (         ) { return 'error'     })
      //
    , obj     =
      {
          name : 'test'
        , test : _reload(
          [
              function (         ) { return this.name       }
            ,,
            , function ( x, y, z ) { return this.name + x + y + z   }
          ])
      }
      //
    ; console.log( "test", test(            ))
    ; console.log( "test", test( 9          ))
    ; console.log( "test", test( 9, 8       ))
    ; console.log( "test", test( 9, 8, 7    ))
    ; console.log( "test", test( 9, 8, 7, 6 ))
    ; console.log( "------------------------")
    ; console.log( "obj.test", obj.test(            ))
    ; console.log( "obj.test", obj.test( 9          ))
    ; console.log( "obj.test", obj.test( 9, 8       ))
    ; console.log( "obj.test", obj.test( 9, 8, 7    ))
    ; console.log( "obj.test", obj.test( 9, 8, 7, 6 ))

  }()

  

 

版本二 看上去更直观

; Reload = ( function ()
  {
    var
      _start = function ( arg, funcs, that )
      {
        var
          ret
        ; funcs.s && funcs.s.call( that )
        ; ret = ( funcs[ arg.length ] || funcs.c || function () {} ).apply( that, arg )
        ; funcs.e && funcs.e.call( that )
        ; return ret
      }
    ; return function ( funcs )
      {
        ; return function ()
          {
            ; return _start( arguments, funcs, this )
          }
      }
  })()
; foo = Reload
  ( { 1 : function (x)    { console.log('-----', this ); return x*x   }
    , 3 : function (x,y,z){ console.log('-----', this ); return x+y+z }
    , s : function ()     { console.log('start', this ) }
    , e : function ()     { console.log('end'  , this ) }
    , c : function ()     { console.log('error', this ) }
    })

 

posted @ 2014-08-08 16:52  doop  阅读(224)  评论(0编辑  收藏  举报