• 请不要在回答技术问题时复制粘贴 AI 生成的内容
yakczh
V2EX  ›  程序员

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

  •  
  •   yakczh · May 29, 2013 · 3202 views
    This topic created in 4767 days ago, the information mentioned may be changed or developed.
    比如传入"isIP" 执行下面的代码

    Validator.check(data).isIP();

    除了eval有别的办法 吗?
    6 replies    1970-01-01 08:00:00 +08:00
    rrfeng
        1
    rrfeng  
       May 29, 2013
    这不就是参数解析么?加个 if/case 就解决了嘛……
    yakczh
        2
    yakczh  
    OP
       May 29, 2013
    这是验证函数,有50多个,还有的是动态注册的
    alsotang
        3
    alsotang  
       May 29, 2013
    __getattr__ 这个东西应该是你要的。
    codepiano
        4
    codepiano  
       May 29, 2013
    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
       May 30, 2013
    如果带参数呢

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

    参数怎么传?
    codepiano
        6
    codepiano  
       May 30, 2013
    @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);
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2580 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 11:37 · PVG 19:37 · LAX 04:37 · JFK 07:37
    ♥ Do have faith in what you're doing.