有关向对象添加方法的简单问题。
为什么我会收到错误消息? 我检查了语法,它看起来是正确的。 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'
最佳答案
是的,因为您已将该方法声明为带有小n
字母的sayname
。
JavaScript 是一种区分大小写的语言。
关于javascript - 向类原型(prototype)添加方法,出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15828327/