1

I have this code

function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
    console.log("I am a " + this.adjective + " rabbit");
};
}

var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();

is it possible to loop over all the objects from the same type?

the method below doesn't seem to work:

for (var e in Rabbit) {
return e.describeMyself();
}
1
  • Put your rabbits in a collection like an array and iterate over the array. Commented Sep 20, 2013 at 21:06

3 Answers 3

2

You can do it this way: Using for-in you can only iterate through the properties of an object but not get the variables defined in a scope. What you have defined are variables which are not bound to any objects.

var obj = { //Define your rabbits here.
    rabbit1: new Rabbit("fluffy"),
    rabbit2: new Rabbit("happy"),
    rabbit3: new Rabbit("sleepy")
}

for (var prop in obj) { //Now iterate through them
    obj[prop].describeMyself();
}

Fiddle

For a much safer side :

for (var prop in obj) {
    if (obj.hasOwnProperty([prop])) { 
        obj[prop].describeMyself();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

No. JavaScript doesn't really keep a list of all the objects you make, you'll have to do that yourself. Or, to better put that, doesn't keep a list that you can just sort through, presto-chango. Try an array:

var objects = []; //Our array

for(var i = 0; i<5; i++){
    //Let's make 5 objects!

    objects.push(new Object()); //Add this object to the array
}

//Later on when needed:

for(var i = 0; i<objects.length; i++){
    objects[i].myFunction();
}

Comments

1
var arr = [ rabbit1, rabbit2, rabbit3 ];

for (var i = 0; i < arr.length; ++i)
{
    arr[i].describeMyself();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.