Reputation: 27685
How can I check if a dynamically named object or function exists?
In example:
var str = 'test';
var obj_str = 'Page_'+str;
function Page_test(){
}
if(typeof obj_str() == 'function') alert('ok');
else alert('error');
Then how can I then call the Object?
In example:
var tst = obj_str();
Upvotes: 1
Views: 2465
Reputation: 28090
Your example is right, except drop the parenthesis after obj_str()
:
if(typeof obj_str != 'undefined') alert('ok');
else alert('error');
This is a bit more correct than window[obj_str]
because obj_str may be defined in a local closure, or if you have nested closures, in a containing closure but not in window itself.
Upvotes: 1
Reputation: 12395
if you run your code in browser, just access global object by window
, your code may like this:
if (typeof window[obj_str] === 'string') {
alert('ok');
}
otherwise, you should gain access to global object:
var global = function() { return this; }() || (1,eval)('this');
if (typeof global[obj_str] === 'stribg
Upvotes: 0
Reputation: 1074276
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
).
Upvotes: 2