/**
* 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
© 2006 - 2023 Martin Ivanov