简体   繁体   中英

Adding a prototype method to an object

I'm doing a javascript tutorial on Code Academy. Here's the problem ( link ):

Add the sayHello method to the Dog class by extending its prototype.

sayHello should print to the console: "Hello this is a [breed] dog", where [breed] is the dog's breed.

Here's my code:

function Dog (breed) {
    this.breed = breed;
};

// add the sayHello method to the Dog class 
// so all dogs now can say hello
Dog.prototype.sayHello = function() {
    console.log("Hello this is a %s dog", this.breed);
}


var yourDog = new Dog("golden retriever");
yourDog.sayHello();

var myDog = new Dog("dachshund");
myDog.sayHello();

My output:

Hello this is a golden retriever dog

Hello this is a dachshund dog

And the error I'm getting:

Oops, try again. It appears that your sayHello method doesn't properly log to the console 'Hello this is a [breed] dog' where [breed] is the breed of the Dog

Is this a problem with CA's code checker or am I doing something wrong?

Whatever method CodeAcademy is using to check your results, it doesn't like how you've processed the text. When I do:

console.log("Hello this is a " + this.breed + " dog");

It says it's "correct".

Your code looks good to me, I think it's an issue with CA.

If you change it to:

Dog.prototype.sayHello = function() { console.log("Hello this is a " + this.breed + " dog"); }

then CA doesn't complain and says it's correct.

Using substitution strings in console.log is not supported in all versions of Javascript. For example Internet Explorer 9 doesn't support them.

Ref: MDN: console.log

Using the older form without a substitution string works:

console.log("Hello this is a " + this.breed + " dog");

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