语法错误,但无法调试JavaScript原型

syntax error but coudn't debug javascript prototype

本文关键字:调试 JavaScript 原型 错误 语法      更新时间:2023-09-26
// create your Animal class here
function Animal(name, numLegs){
    this.name = name;
    this.numLegs = numLegs;
}

// create the sayName method for Animal
Animal.prototype.sayName(){
    console.log("Hi my name is " + this.name);
}
// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

不工作,找不到问题所在。除了 chrome 控制台之外,还有什么工具可以调试吗?有时它无法分辨哪条线有问题。

你必须创建这样的原型方法

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

试试这个:

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

Animal.prototype.sayName = function(){
    console.log("Hi my name is " + this.name);
}
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();