Throw Exception containing variable name

This question already has an answer here:

  • How to execute a JavaScript function when I have its name as a string 29 answers

  • You are trying to convert a string to a function and create a new instance of a variable, which won't work.

    There are ways to get a function corresponding to a string: How to turn a String into a javascript function call?

    But a better way to go about this would be to simply do the first if statement, or convert it to a switch.

    For a global variable:

    // Set up in global scope, not in the scope of something else.
    var NoXException = function () { ... }
    
    var variable = "No" + getMissing() + "Exception";
    throw new window[variable]()
    

    For a variable that's stored within another's scope:

    var exceptions = {}
    exceptions.NoXException = function () { ... }
    
    var variable = "No" + getMissing() + "Exception";
    throw new exceptions[variable]()
    // Alternatively
    throw new window['exceptions'][variable]()
    
    链接地址: http://www.djcxy.com/p/94830.html

    上一篇: 如何从字符串触发函数?

    下一篇: 抛出包含变量名称的异常