0

关于向对象添加方法的快速问题。

为什么我会返回错误?我检查了语法,它似乎是正确的。Javascript 新手。

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

// create the sayName method for Animal
Animal.prototype.sayname = function() {
    console.log("Hi my name is " + this.name);
};

// test
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

尝试运行代码时出现此错误

TypeError: Object #<Animal> has no method 'sayName'
4

2 回答 2

3

是的,因为您已将方法声明为sayname使用小写n字母。

JavaScript 是一种区分大小写的语言。

于 2013-04-05T07:37:03.587 回答
1

您调用sayName()并添加的功能是function sayname(){}.

于 2013-04-05T07:40:02.803 回答