25. Call object method with for...loop


#1

Hi everyone!

I was thinking that if instead of 3 I would have created 100 new Rabbit objects I wouldn't want to type Rabbit.describeMyself() 100 times. So I was trying to use a for loop to add a number to Rabbit, and then call each iteration result as its method, like so:

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

// now we can easily make all of our rabbits
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

for (i=1;i<4;i++){
    var a=("rabbit"+i);
    a.describeMyself();
};

I'm getting an error that reads TypeError a.describemyself is not a function so what I'm guessing it is happening is that "a.descrybeMyself" is being read as a name of a function in string format. This means that var a is not being identified as an object, and I guess that's because of "rabbit" being given to var a as a string.

Are my assumptions correct? If so, I would I go about converting a so that it can be read as an object?

Thanks


#2

@cobb151,
Try it with

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

// now we can easily make all of our rabbits
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

for (i=1;i<4;i++){
    var a=("rabbit"+i);
    eval(a).describeMyself();
}

#3

Thanks works perfectly, and its a really simple solution. :raised_hands:


#4

@cobb151

Reference

google search
== the Book ==
javascript [your question] site:developer.mozilla.org

== discussions / opinions ==
javascript [your question] site:stackoverflow.com

== guidance ==
www.crockford.com
http://javascript.crockford.com/code.html <---JavaScript code-convention
http://javascript.crockford.com/survey.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
www.developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
http://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript
http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function
http://stackoverflow.com/questions/6260475/how-to-the-operator
http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.