xoxo419
V2EX  ›  问与答

javascript 如何把变量的值当成函数调用?

  •  
  •   xoxo419 · Dec 18, 2017 · 2725 views
    This topic created in 3082 days ago, the information mentioned may be changed or developed.
    function a() {
        console.log('this is a function');
    }
    
    function b() {
        console.log('this is b function');
    }
    
    //变量
    
    var fun;
    
    fun = 'a';
    
    fun();  //如何可以让变量返回的字符串当成一个函数?
    
    Supplement 1  ·  Dec 18, 2017

    感谢! 已解决

    解决使用的方法 #4 #6

    9 replies    2017-12-18 10:18:54 +08:00
    ballshapesdsd
        1
    ballshapesdsd  
       Dec 18, 2017
    eval?
    Pastsong
        2
    Pastsong  
       Dec 18, 2017 via Android
    window[fun]()
    xoxo419
        3
    xoxo419  
    OP
       Dec 18, 2017
    @ballshapesdsd 我想在微信小程序的, 但不支持这个函数...
    bayallen
        4
    bayallen  
       Dec 18, 2017 via iPhone   ❤️ 1
    把字符串当作方法的名称,通过 obj["a"]调用?
    jtsai
        5
    jtsai  
       Dec 18, 2017
    eval('a')
    noe132
        6
    noe132  
       Dec 18, 2017 via Android   ❤️ 1
    把函数定义到对象上。
    let obj = {a:a b,b}
    let name = 'a'
    obj[name]()
    crz
        7
    crz  
       Dec 18, 2017
    @xoxo419 new Function 呢
    ipwx
        8
    ipwx  
       Dec 18, 2017
    6L 的方法最普通而有效。
    Revenant
        9
    Revenant  
       Dec 18, 2017
    `${a()}`
    `${b()}`
    直接就执行了。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3263 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 12:03 · PVG 20:03 · LAX 05:03 · JFK 08:03
    ♥ Do have faith in what you're doing.