简体   繁体   English

向构造函数原型添加方法

[英]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. 我正在学习JavaScript,最近在向构造器原型添加方法时遇到了一个麻烦。 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. 我正在尝试通过将this.name添加到console.log语句中来做到这一点。 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? 这是codeacademy告诉我的:“糟糕,再试一次。看来您的Animal.prototype.sayName方法未正确登录控制台'Hi my name is [name]',其中[name]是Animal的名称” this.name不应引用最终由构造函数创建的任何动物名称吗? 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. 它没有通过,因为代码学院想要“嗨,我的名字是this.name”,并且我用额外的逗号写了“嗨,我的名字是this.name”。 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. 该代码不起作用,因为console.log语句中还有一个逗号。

Thanks for all of your help, everyone! 谢谢大家的帮助!

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

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