25. Constructors in Review - undefined issue


#1



I'm able to pass the test with my code, but there're 'undefined' errors in between the expected output. The outcome of my code is as below:

I am a fluffy rabbit
undefined
I am a happy rabbit
undefined
I am a sleepy rabbit
undefined

Not sure why does the undefined show up.

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');

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


#2

Hi @darrenhuangtw,

The undefined is via the use of your console.log. You already set your describeMyself Rabbit method to print to console, and when you invoke this this is what it will do, but additionally for each new Rabbit instance you create you set them inside the console.log to invoke their describeMyself method.

If it may help the following two samples could be used to hopefully better show how this could be run without returning undefined :slight_smile:

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');

rabbit1.describeMyself();  //In this version we have removed the use of console.log()
rabbit2.describeMyself();  //so that all you will do is invoke the describeMyself method
rabbit3.describeMyself();  //which essentially will do the console.log() print for you



function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        return "I am a " + this.adjective + " rabbit"; //here we have chosen to return the adjective as a string BACK to console.log()
    };
}

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

console.log(rabbit1.describeMyself()); //because we  return a value out with the describeMethod()
console.log(rabbit2.describeMyself()); //we can use returned literal string to be printed by console.log()
console.log(rabbit3.describeMyself()); //in this way we only print the output once and nothing is undefined

#3

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