JavaScript Determine if dynamically named function exists

前端 未结 4 671
名媛妹妹
名媛妹妹 2021-01-01 08:15

How can I check if a dynamically named object or function exists?

In example:

var str = \'test\';
var obj_str = \'Page_\'+str;

function Pag         


        
相关标签:
4条回答
  • 2021-01-01 08:24

    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.

    0 讨论(0)
  • 2021-01-01 08:35

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

    0 讨论(0)
  • 2021-01-01 08:36

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

    Demo.

    0 讨论(0)
  • 2021-01-01 08:46

    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
    
    0 讨论(0)
提交回复
热议问题