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")+"");

posted @   Young.Jiang  阅读(781)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2008年12月 >
30 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3
4 5 6 7 8 9 10
点击右上角即可分享
微信分享提示