简体   繁体   English

向对象添加原型方法

[英]Adding a prototype method to an object

I'm doing a javascript tutorial on Code Academy. 我正在做Code Academy上的javascript教程。 Here's the problem ( link ): 这是问题所在( link ):

Add the sayHello method to the Dog class by extending its prototype. 通过扩展其原型,将sayHello方法添加到Dog类。

sayHello should print to the console: "Hello this is a [breed] dog", where [breed] is the dog's breed. sayHello应该打印到控制台:“您好,这是一只[品种]狗”,其中[品种]是狗的品种。

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 看来您的sayHello方法未正确登录到控制台“您好,这是一只[品种]狗”,其中[品种]是那只狗的品种

Is this a problem with CA's code checker or am I doing something wrong? 这是CA的代码检查器出现问题还是我做错了什么?

Whatever method CodeAcademy is using to check your results, it doesn't like how you've processed the text. 无论CodeAcademy使用什么方法来检查结果,它都不喜欢您处理文本的方式。 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. 您的代码对我来说看起来不错,我认为这是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. 然后CA不会抱怨,说是正确的。

Using substitution strings in console.log is not supported in all versions of Javascript. 所有版本的Javascript均不支持在console.log使用替换字符串。 For example Internet Explorer 9 doesn't support them. 例如,Internet Explorer 9不支持它们。

Ref: MDN: console.log 参考: MDN:console.log

Using the older form without a substitution string works: 使用不带替换字符串的较旧形式的作品:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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