如何在javascript中获取给定类型的所有对象 [英] how to get all objects of a given type in javascript

查看:205
本文介绍了如何在javascript中获取给定类型的所有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检索使用new关键字创建的给定类型的所有对象(不是DOM元素)。

I want to retrieve all objects (not DOM elements) of a given type created with the "new" keyword.

是否可以?

function foo(name)
{
  this.name = name;
}

var obj = new foo();

如何检索对所有foo对象的引用?

How can I retrieve a reference to all the foo objects ?

推荐答案

如果它们都在全局范围内分配,并且您不需要检查 iframe / window 边界,你不需要在IE中执行此操作(例如,您只是尝试调试某些内容),您应该能够遍历全局范围:

If they were all assigned in the global scope, and you don't need to check across iframe/window boundaries, and you do not need to do this in IE (eg you're just trying to debug something), you should be able to iterate over the global scope:

var fooObjects = [];
for(var key in window) {
  var value = window[key];
  if (value instanceof foo) {
    // foo instance found in the global scope, named by key
    fooObjects.push(value)
  }
}

Buuuuut你可能在某些地方的函数内部实例化了一些foos,在这种情况下它们不可用。

Buuuuut you probably have some foos instantiated inside functions somewhere, in which case they're not available.

您可以尝试在实例化之前修改构造函数:

You can perhaps try modifying the constructor prior to instantiations:

var fooObjects = [];
var oldFoo = window.foo;
window.foo = function() {
  fooObjects.push(this);
  return oldFoo.apply(this, arguments);
}

foo.prototype = oldFoo.prototype;

这篇关于如何在javascript中获取给定类型的所有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆