16. Its all in the genes (solution) CMIIW


#1



Hi everyone, i just wanna check if someone got a same problem with me in this exercise.

So i made this code :

// create your Animal class here
function Animal(name,numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}

// create the sayName method for Animal
Animal.prototype.sayName = function () {
    console.log("Hi, my name is "+ this.name);
}

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

it goes well and successfully print what i wanted to the console,
in this case it will saying : "Hi, my name is Captain Cook"
but i got an error like this :

Oops, try again. It looks like your Animal.prototype.sayName method does not properly log to the console 'Hi my name is [name]' where [name] is the name of the Animal

and then i try to change my code to this :

// create your Animal class here
function Animal(name,numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}

// create the sayName method for Animal
Animal.prototype.sayName = function (x) { // <<modified this line
    console.log("Hi, my name is "+ x.name); // << this line also
}

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

and successfully appear "Way to Go !" to continue to the next exercise, BUT it failed to print to the console.

the console detect an error and it saying this :

TypeError: Cannot read property 'name' of undefined

so i want to check if anyone got same problem like me? i know it doenst affect to much because i have find way out so i still can continue the exercise, but its bothering me, which code are actually true due the syntax? thanks for your help


#6

I got the same problem. What you've done is right but it isn't accepted because of the comma after "Hi". So you have to remove the comma.


#7

try using 'this' so it refers to the object being called

// create the sayName method for Animal
Animal.prototype.sayName = function (x) { // <<modified this line
    console.log("Hi, my name is "+ x.name); // << this line also
}

would turn into

Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

you can see that

penguin.sayName();

has no parameters.

My final code was

function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

var theCaptain = new Penguin("Captain Cook", 2);
theCaptain.sayName();

you can test it at https://repl.it/languages/javascript

it will print the name Captain Crook


#8

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