0

Is it possible to access JS in-memory objects from within the code? Are there any internal memory inspectors available? Can I list the objects with a given prototype (or type) from code?

// EXAMPLE
function Kitten(name) { this.name = name; }
var kitten = new Kitten('furry');
// ...
// Any features like this?
var kittens = ListObjectsOfType(Kitten);
// Or this?
var kittens2 = ListObjectsWithPrototype(kitten.prototype);

Primarily I'm interested in Google's V8 implementations or ES6 (Harmony) specifications. (I appreciate other technologies too.)

Gábor Imre
  • 4,754
  • 2
  • 28
  • 44

1 Answers1

0

You can create a function for this. Something like:

function ListObjectsOfType(type) {
    var result = [];
    for( var w in window ) {
        var val = window[w];
        if( val instanceof type )
            result.push(val);
    }
    return result;
}

If you invoke this from the Chrome Console, you can plainly inspect/collapse the resulting objects. You can extend it to traverse all window vars (you'll want to skip the defaults though). I think by definition it is impossible to inspect e.g. the following:

function SomeObj() {
    var b = new Kitten('kitty');
}
new SomeObj();

I expect the memory heap to have this obj, but it will not be available/detectable via JS ever.

EricG
  • 3,603
  • 1
  • 19
  • 32
  • Yeah, this lists the properties of the `window` (i.e. the global variables), but it's far from being a memory inspector. The local variables (`function() { var k = new Kitten('meow')}`) and member variables are not listed here. – Gábor Imre Oct 01 '14 at 13:11
  • Agreed. The Chrome Devtools have a feature to see the memory and its objects, but you cannot runtime inspect it with a function, as far as I know. This example can be extended by inspecting every object that is one way or another referenced, but some objects are I think by definition not accessible since they live in a local scope. – EricG Oct 01 '14 at 13:15