25. rabbit situation


#1

can someone explain me why 'undefined' is being displayed and how to get rid of it?


#2

Hi,
the problem here is you are calling console.log() at the bottom and in your function. What is happening is first your function within the console.log() is called. The function will execute (By the way, you don't need this.adjective = adjective within the function. That is taken care of when you instantiate the object), including the
console.log("I am a " + this.adjective + " rabbit");
That console.log within the function is printing "I am a fluffy rabbit". Now your function ends, but nothing was returned to the console.log at the bottom, so at the bottom your console.log() has nothing to print, giving you undefined.

To fix this, either remove console.log before the functions at the bottom, or instead of console.log in the function, use return. Both will give you the same results (though I think the first one is a bit easier to read).


#3

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();
rabbit2.describeMyself();
rabbit3.describeMyself();