25

如何查看某个对象是否已加载,如果没有,如何加载,如下所示?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject();
}
4

10 回答 10

37

如果它是一个对象,那么您应该能够检查它是否为未定义,然后如果是则加载它。

if (myObject === null || myObject === undefined) {
   myObject = loadObject();
}

使用typeof函数也是一种选择,因为它返回所提供对象的类型。但是,如果对象尚未加载,它将返回null 或 undefined,因此在可读性方面可能会归结为个人偏好。

于 2008-09-18T19:18:07.710 回答
27
if(typeof(o) != 'object') o = loadObject();
于 2008-09-18T19:16:05.560 回答
5
myObject = myObject || loadObject();
于 2010-10-31T03:42:21.273 回答
3

我不确定您所说的“已加载”是什么意思...变量是否object存在并且根本没有您想要的类型?在这种情况下,你会想要这样的东西:

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

然后使用if (isObjectType(object, MyType)) { object = loadObject(); }.

如果object在您的测试之前没有填充任何内容(即 - typeof object === 'undefined'),那么您只需要:

if ('undefined' === typeof object) { object = loadObject(); }
于 2008-09-18T19:20:43.613 回答
3

您可能想查看是否定义了给定对象

特别是如果它在一个异步线程中完成,并带有 setTimeout 来检查它何时出现。

  var generate = function()
  { 
      window.foo = {}; 
  }; 
  var i = 0;
  var detect = function()
  {
     if( typeof window.foo == "undefined" ) 
     {
           alert( "Created!"); 
           clearInterval( i );
     }
   };
   setTimeout( generate, 15000 ); 
   i = setInterval( detect, 100 ); 

理论上应该检测 window.foo 何时存在。

于 2008-09-18T19:22:12.923 回答
3

If by loaded you mean defined, you can check the type of the variable with the typeof function. HOWEVER typeof has a few quirks, and will identify an Object, an Array, and a null as an object

alert(typeof(null));

Identifying a null as a defined object would probably cause your program to fail, so check with something like

if(null !== x && 'object' == typeof(x)){
    alert("Hey, It's an object or an array; good enough!");
}
于 2008-09-18T21:13:02.503 回答
2

如果要检测自定义对象:

// craete a custom object
function MyObject(){

}

// check if it's the right kind of object
if(!(object instanceof MyObject)){
   object = new MyObject();
}
于 2008-09-18T19:22:14.610 回答
2

您也可以只使用快捷方式if(obj)

于 2008-09-18T19:22:21.427 回答
1

typeof(obj)将在其他可能的值中返回类对象的“对象”。

于 2008-09-18T19:15:53.050 回答
1
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.

于 2012-09-23T00:02:02.100 回答