Reputation: 3
How do I call a method on an array of objects in javascript? I created an object with certain properties and methods. Then created additional objects. I set up my additional objects in an array. Now, I want to use a for loop to call a method on each of the objects in the array without having to write console.log each time. Thanks.
//create object Rabbit with adjective property and describeMyself method
function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}
//create three new objects in Rabbit class
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");
//create array of objects for rabbit class
var rabbits = [rabbit1, rabbit2, rabbit3];
//attempt to log describeMyself method for each object in the rabbits array using a for
// loop.
for(i = 0; i < rabbits.length; i++){
console.log([i].describeMyself());
}
Upvotes: 0
Views: 119
Reputation: 101662
What you're trying to do is this:
console.log(rabbits[i].describeMyself());
But there's a problem here, because describeMyself()
itself logs to the console and doesn't return anything, so what you would see in the console is:
I am a fluffy rabbit
undefined
I am a happy rabbit
undefined
I am a sleepy rabbit
undefined
To remedy this, I suggest changing the definition of Rabbit
to the following:
function Rabbit(adjective) {
this.adjective = adjective;
}
Rabbit.prototype.describeMyself = function() {
return "I am a " + this.adjective + " rabbit";
};
so that it returns a string instead. Placing the function on the prototype, while a completely separate matter, should offer you some performance benefits as well since you won't be making a new copy of describeMyself
for each Rabbit
.
Upvotes: 2