0

当我运行以下代码时,出现错误: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();

为什么?

4

2 回答 2

5

我认为这是问题所在

   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

演示

于 2013-07-13T13:17:27.627 回答
2

Animal原型设置不正确:

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

将原型设置为函数并非完全错误,但问题是代码打算在原型对象上使用名为“sayName”的属性。提供一个名为“sayName”的函数将无法用于此目的;该名称不会作为函数对象的属性公开。

另请注意,简单地将“[name]”放在记录到控制台的字符串中不会导致记录动物名称。您必须从对象的“名称”属性中将其显式修补到字符串中,如我发布的代码中所示。

于 2013-07-13T13:16:40.680 回答