How to check if a variable is loaded in JavaScript?

后端 未结 10 1712
遇见更好的自我
遇见更好的自我 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:47

    I'm not sure what you mean by "loaded"... does the variable object exist and simply doesn't have the type you want? In that case, you'll want something like:

    function isObjectType(obj, type) {
        return !!(obj && type && type.prototype && obj.constructor == type.prototype.constructor);
    }
    

    and then use if (isObjectType(object, MyType)) { object = loadObject(); }.

    If object is not populated with anything before your test (ie - typeof object === 'undefined') then you just need:

    if ('undefined' === typeof object) { object = loadObject(); }
    

提交回复
热议问题