V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yakczh
V2EX  ›  程序员

如何根据传入的参数调用对应的方法?

  •  
  •   yakczh · 2013-05-29 22:04:43 +08:00 · 2618 次点击
    这是一个创建于 3981 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如传入"isIP" 执行下面的代码

    Validator.check(data).isIP();

    除了eval有别的办法 吗?
    6 条回复    1970-01-01 08:00:00 +08:00
    rrfeng
        1
    rrfeng  
       2013-05-29 22:13:23 +08:00
    这不就是参数解析么?加个 if/case 就解决了嘛……
    yakczh
        2
    yakczh  
    OP
       2013-05-29 22:45:50 +08:00
    这是验证函数,有50多个,还有的是动态注册的
    alsotang
        3
    alsotang  
       2013-05-29 23:40:31 +08:00
    __getattr__ 这个东西应该是你要的。
    codepiano
        4
    codepiano  
       2013-05-29 23:48:06 +08:00
    obj = {
    a:function(){
    alert('a');

    },
    b:function(){
    alert('b');

    },
    c:function(){
    alert('c');
    }
    }

    function test(name){
    obj[name]();
    }

    test('c');
    test('a');
    test('b');

    你是想要这个效果吗?
    yakczh
        5
    yakczh  
    OP
       2013-05-30 08:35:59 +08:00
    如果带参数呢

    test('isIP') 调用 Validator.check(data).isIP();
    test('isRange',[100,200]),调用 Validator.check(data).isRange(100,200);

    参数怎么传?
    codepiano
        6
    codepiano  
       2013-05-30 11:38:23 +08:00
    @yakczh 如下
    obj = {
    a:function(args){
    alert(args);
    },
    b:function(args){
    alert(args);
    },
    c:function(args){
    alert(args);
    }
    }

    function test(){
    args = Array.prototype.slice.apply(arguments);
    name = args.shift();
    obj[name](args);
    }

    test('c',1);
    test('a',2,3);
    test('b',4,5,6);
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5342 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:13 · PVG 17:13 · LAX 02:13 · JFK 05:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.