Javascript模拟c#方法重载

每次看John Resig的blog,都会有很大的收获!这次和大家一起分享一个Javascript模拟c#方法重载的例子。

  function  loadMethod(object, name, fn){ 
            
var  old  =  object[ name ]; 
            
if  ( old ) 
                object[ name ] 
=   function (){ 
                    
if  ( fn.length  ==  arguments.length ) 
                        
return  fn.apply(  this , arguments ); 
                    
else   if  (  typeof  old  ==  ' function ' ) 
                        
return  old.apply(  this , arguments ); 
                }; 
            
else  
                object[ name ] 
=  fn; 
        }

下面写一个在用户集合中查找特定用户数量的例子
function  UserCount(){ 
            loadMethod(
this " find " function (list){ 
                
// 查找所有数量
                 var  i = 0 ;
                
return  list.length;
            }); 
            loadMethod(
this " find " function (list,pwd){ 
                
// 查找特定密码的用户数量
                 var  k = 0 ;
                
for ( var  i = 0 ;i < list.length;i ++ )
                {
                    
if (list[i].pwd == pwd)
                        k
++ ;
                }
                
return  k;
            }); 
            loadMethod(
this " find " function (list,id, pwd){
                
// 查找特定密码和id的用户数量 
                 var  k = 0 ;
                
for ( var  i = 0 ;i < list.length;i ++ )
                {
                    
if (list[i].id == id  &&  list[i].pwd == pwd)
                        k
++ ;
                }
                
return  k;
            })
        }

// 定义集合
         var  userlist = new  Array();
        userlist.push({id:
" holygrace " ,pwd: " 12345 " });
        userlist.push({id:
" JiangYuYang " ,pwd: " 2233 " });
        userlist.push({id:
" liyanhong " ,pwd: " 12345 " });
        userlist.push({id:
" mayun " ,pwd: " adf " });
        userlist.push({id:
" wangzidong " ,pwd: " 3456 " });
        
        
var  count = new  UserCount()
        alert(
" find(userlist)找到\n " + count.find(userlist) + " " );
        alert(
" find(userlist,\ " 12345 \ " )找到\n " + count.find(userlist, " 12345 " ) + " " );
        alert(
" find(userlist,\ " holygrace\ " ,\ " 12345 \ " )找到\n " + count.find(userlist, " holygrace " , " 12345 " ) + " " );

你可能感兴趣的:(JavaScript)