javascript - codecademy的这段代码有什么错误

标签 javascript

当我运行以下代码时,出现错误:TypeError: Object [object Object]

// create your Animal class here

function Animal(name, numLegs)
{
    this.name = name;
    this.numLegs = numLegs;
}

// create the sayName method for Animal

Animal.prototype = function sayName()
{
    console.log("Hi, my name is [name]");
};
// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

为什么?

最佳答案

我认为这就是问题所在

   Animal.prototype = function sayName(){

     console.log("Hi, my name is [name]");

   };

应该是

   Animal.prototype.sayName = function(){

     console.log("Hi, my name is ", this.name);

   };

此外,[name] 不是 javascript :S

Demo

关于javascript - codecademy的这段代码有什么错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630542/

相关文章:

javascript - Google 脚本运行时优化

javascript - 我只需要构建一个像这样的散点图?我尝试过使用 Google 图表,但找不到合适的图表

javascript - 我可以通过回调添加 getJSON 的 did() 函数吗?

javascript - 拉斐尔.js : Adding a new custom element

javascript - 尝试/捕获不捕获快速异步功能中的所有错误?

javascript - 将 JavaScript 变量传递给外部 CSS 文件

javascript - 在单页应用程序中上传文件

javascript - 选择的奇怪行为

javascript - Knockout 问题,无法使用 'in' 运算符搜索 'length'

javascript - 当在两个文本字段之间更改光标时,Angular JS 会收到警报