简体   繁体   中英

Adding a method to a constructor prototype

I am learning JavaScript and I recently came across a snag when adding a method to a constuctor prototype. I am trying to add a method that will print to the console the name of the animal created by the animal class constructor. I am trying to do this by adding this.name to the console.log statement. However, this pass when I try to submit the code. Here is what codeacademy tells me: "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" Shouldn't this.name refer to whichever animal's name that ends up being created by the constructor? What am I doing wrong? EDIT: Got it, everyone. It didn't pass because codeacademy wanted "Hi my name is this.name" and I wrote "Hi, my name is this.name" with an extra comma. Thanks for all of your help!

function Animal (name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
};
Animal.prototype.sayName = function () {
console.log("Hi, my name is " + this.name);
};
// trying to use this.name but doesn't work
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

The code did not work because I had an additional comma in the console.log statement.

Thanks for all of your help, everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM