我正在尝试创建一个具有构造函数和原型功能的简单动物类,以返回动物的名称和描述。
到目前为止,我创建了类的构造函数:
class Animal {
Animal(name, description) {
this.name = name;
this.description = description;
}
}
但是,当我尝试创建动物原型并调用功能以返回动物的姓名和描述...
Animal.prototype.message = function() {
return this.name " + has the following description: " + this.description;
}
... Visual Studio代码突出显示Animal.prototype.message()
中的周期并告诉我';' expected
。
我已经呆了一个小时了,我觉得我缺少一些明显的东西,但是无论我想知道自己在做什么。预先感谢您的任何帮助。
编辑:修复了代码错字。
我在这里看到了几个问题。
- 在您的班上,您没有构造函数(
Animal
应该是constructor
( - 您正在使用原型为课程添加功能。为什么不这样做正确的方式(... ES6 Way(
我将是您收到的愚蠢错误是因为"构造函数"设置(使用Animal
而不是constructor
(,或者是因为您正在执行
Animal.prototype.message() = function { ... }
(应为 Animal.prototype.message() = function() { ... }
(
示例:
class Animal {
constructor(name, description) {
this.name = name;
this.description = description;
}
message() {
return `${this.name} has the following description: ${this.description}`;
}
}
const animal = new Animal('liger', 'a lion and a tiger');
const message = animal.message();
console.log(message);