How to check if a variable is loaded in JavaScript?

后端 未结 10 1690
遇见更好的自我
遇见更好的自我 2021-01-31 04:01

How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject()         


        
相关标签:
10条回答
  • 2021-01-31 04:50
    if(typeof(o) != 'object') o = loadObject();
    
    0 讨论(0)
  • 2021-01-31 04:50
    if (!("someVar" in window)) {
      someVar = loadObject();
    }
    

    will tell you whether any JS has previously assigned to the global someVar or declared a top-level var someVar.

    That will work even if the loaded value is undefined.

    0 讨论(0)
  • 2021-01-31 04:54

    If you want to detect a custom object:

    // craete a custom object
    function MyObject(){
    
    }
    
    // check if it's the right kind of object
    if(!(object instanceof MyObject)){
       object = new MyObject();
    }
    
    0 讨论(0)
  • 2021-01-31 05:04

    You can also just use a shortcut if(obj)

    0 讨论(0)
提交回复
热议问题