25. Constructors in Review (using for loop to invoke object methods)


#1


My confusion is over the last couples lines in the for...loop. The code is correct up to that point.

There are no errors, the code actually progresses the lesson, but the console doesn't show the actual message I expected.

I can't find anything wrong with logic. Why doesn't the last line, j.describeMyself, behave the same way as typing out rabbit1.describeMyself? I know I can just type it out three times, but I wanted to try something from before.


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<=3;i++) {
    var j = 'rabbit'+i;
    j.describeMyself;
};


#2

Hi @byteninja44492,

Here the variable j is considered as a string so you must cast it in "Rabbit" before you can use the describeMyself method. To do this, you can use the eval function.

You forgot the () at the end of the method describeMyself.

In the end, you gotta have something like this:

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

#3

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