JavaScript Determine if dynamically named function exists

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

提交回复
热议问题