How can I check if a dynamically named object or function exists?
In example:
var str = \'test\';
var obj_str = \'Page_\'+str;
function Pag
You were close, but don't try to call obj_str
(it's just a string, it's not callable); instead, use it to look up the property on window
(since all global functions and global variables are properties of window
):
if(typeof window[obj_str] == 'function') alert('ok');
// ^-- No (), and use `window`
else alert('error');
If you don't care that it's specifically a function:
if (obj_str in window) alert('ok');
else alert('error');
The in
operator checks to see if a given string matches a property name in the given object (in this case, if the contents of obj_str
are a property in window
).