this question has answer here:
how can throw exception using variable within exception name during throw new
statement?
i have list of exceptions i'm trying throw depending on whether or not 1 variable 0 in length. name of exception, example, contains variable name.
works
if (x.length === 0) { throw new noxexception(); } if (y.length === 0) { throw new noyexception(); } if (z.length === 0) { throw new nozexception(); }
doesn't work
var x = 'oh'; var y = 'hai'; var z = ''; // contains "nozexception" var ex = "no" + ((x.length != 0) ? ((y.length != 0) ? 'z' : 'y') : 'x') + "exception"; // throwing ex gives error throw new ex();
you trying convert string function , create new instance of variable, won't work.
there ways function corresponding string: how turn string javascript function call?
but better way go first if statement, or convert switch.
for global variable:
// set in global scope, not in scope of else. var noxexception = function () { ... } var variable = "no" + getmissing() + "exception"; throw new window[variable]()
for 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]()
Comments
Post a Comment