xoxo419
V2EX  ›  问与答

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

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