我已经做了很多 HTML 和 CSS 的工作,现在我正在做 JS 教程。不过我遇到了这个问题。我不知道如何访问原型(prototype)。
说明:
Create a class named Animal with two properties,
name
andnumLegs
. The Animal constructor should have two arguments whose values are assigned toname
andnumLegs
.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/