【问题标题】:Adding a method to a Class protoype, error向类原型添加方法,错误
【发布时间】:2013-04-05 07:36:15
【问题描述】:

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

为什么我会返回错误? 我检查了语法,它似乎是正确的。 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'

【问题讨论】:

    标签: javascript class methods


    【解决方案1】:

    是的,因为您已将方法声明为 sayname 并带有小 n 字母。

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

    【讨论】:

      【解决方案2】:

      你调用了sayName(),添加的函数是function sayname(){}

      【讨论】:

        猜你喜欢
        • 2019-05-28
        • 2014-05-26
        • 2019-01-17
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 2015-10-16
        • 1970-01-01
        • 2014-07-20
        相关资源
        最近更新 更多