How to Find Instance Name(s) of a JavaScript Object

For a project I was recently working on, I needed to get reference to object(s)’ instances and respectively their methods and properties, so below is the solution I came up with. getInstancesOf() is a JavaScript function that checks for instances of an object within a defined scope and returns an array of instances’ variable names that can be used for different purposes.

/**
* Get instance names of an object
* @param object - object name
* @param scope - window, parent, etc
*/

function getInstancesOf(object, scope) {
     "use strict";

     var
        instances = [];

    for(var v in scope) {
        if(scope.hasOwnProperty(v) && scope[v] instanceof object) {
            instances.push(v);
        }
    }
    return instances;
}

And a few tests, in which we create a couple of instances of the MyClass object:

(function() {
    "use strict";

    function MyClass(name) {
        this.name = name;
    }
    MyClass.prototype = {
        myMethod: function() {
            console.log("MyClass.prototype.myMethod(): " + this.name);
        }
    };

    window.MyClass = MyClass;
})();

var
    instance1 = new MyClass("property of instance1"),
    instance2 = new MyClass("property of instance2"),
    instance3 = new MyClass("property of instance3");

// get length of instances of MyClass
console.log(getInstancesOf(MyClass, window).length); // 3
// get the name of instance1
console.log(getInstancesOf(MyClass, window)[1]); // instance2
// get the name of instance0
console.log(getInstancesOf(MyClass, window)[0]); // instance1
// loop through all of the instances of MyClass, and call it's test() method
for(var i = 0, len = getInstancesOf(MyClass, window).length; i < len; i ++) {
    window[getInstancesOf(MyClass, window)[i]].myMethod();
}

Related Posts

Advertisements

15 comments

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s