Javascript 向类原型添加方法时出错
关于向对象添加方法的快速问题 为什么我要找回错误? 我检查了语法,它似乎是正确的。 Javascript的新特性Javascript 向类原型添加方法时出错,javascript,class,methods,Javascript,Class,Methods,关于向对象添加方法的快速问题 为什么我要找回错误? 我检查了语法,它似乎是正确的。 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 = functio
// 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'
TypeError:对象#没有方法“sayName”
是的,因为您已经用小的n
字母将方法声明为sayname
JavaScript是一种区分大小写的语言。是的,因为您已经用小的
n
字母将该方法声明为sayname
JavaScript是区分大小写的语言。您调用了sayName()
,添加的函数是function sayName(){}
您调用了sayName()
,添加的函数是function sayName(){}