javascript - 如何更改 "animal"的原型(prototype)并添加方法 "sayName"到打印语句

标签 javascript oop object prototype

我已经做了很多 HTML 和 CSS 的工作,现在我正在做 JS 教程。不过我遇到了这个问题。我不知道如何访问原型(prototype)。

说明:

Create a class named Animal with two properties, name and numLegs. The Animal constructor should have two arguments whose values are assigned to name and numLegs.

Next, change the prototype of Animal and add a method sayName that prints to the console "Hi my name is [name]", where [name] is the value of name.

Click "Stuck? Get a hint!" for examples of how to create a class and how to add a method to an object's prototype.

Finally, we have provided the last two lines to test your constructor and sayName method. Don't change these!

这是我的代码:

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

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


// create the sayName method for Animal

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

我收到语法错误。给出了什么?

最佳答案

我认为语法错误是由于函数声明后的等号造成的:

function Animal(name, numLegs)=

如果删除等号,该函数就不会再抛出语法错误(我刚刚在 Chrome 的控制台中尝试过)。

关于javascript - 如何更改 "animal"的原型(prototype)并添加方法 "sayName"到打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27683626/

相关文章:

javascript - 访问 JavaScript JSON 中的对象属性

javascript - Visual Studio Web Essentials JSDoc intellisense 在构造函数中分配的方法不起作用?

javascript - Mat-Select 返回未定义

javascript - anchor 目标_blank被浏览器阻止

PHP:如何自动包含和实例化类?

Javascript 实例变量显示为未定义

javascript - 在 jQuery AJAX 中使用异步选项

c# - 创建返回正则表达式匹配命令的类的最佳方法

javascript - 如何使用 JSON 在表中显示空白记录?

javascript - 合并循环中的对象