JavaScript Determine if dynamically named function exists

前端 未结 4 690
名媛妹妹
名媛妹妹 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: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).

提交回复
热议问题