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

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

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.

[sourcecode language=”javascript”]
/**
* 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;
}
[/sourcecode]

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

[sourcecode language=”javascript”]
(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();
}
[/sourcecode]

Related Posts

Categories and Tags
Links

© 2006 - 2023 Martin Ivanov