JavaScript Determine if dynamically named function exists

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();

Answers:

Answer

You can get a global by its name by writing window[obj_str].

Demo.

Answer

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).

Answer

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.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.