'; ' 在尝试创建原型函数调用时预期

' ; ' expected when trying to create a prototype function call

我正在尝试创建一个简单的动物 class,它带有一个构造函数和一个原型函数,用于 return 动物的名称和描述。

到目前为止,我为 class:

创建了构造函数
class Animal {
    Animal(name, description) {
        this.name = name;
        this.description = description;
    }
}

但是当我尝试创建一个 Animal 原型并调用一个函数来 return Animal 的名称和描述时...

Animal.prototype.message = function() {
    return this.name " + has the following description: " + this.description;
}

...Visual Studio 代码突出显示 Animal.prototype.message() 中的句点并告诉我 ';' expected.

我已经做了一个小时了,我觉得我遗漏了一些明显的东西,但无论如何我想知道我做错了什么。在此先感谢您的帮助。

编辑:修复了代码拼写错误。

我在这里看到了几个问题。

  1. 在你的 class 中,你没有构造函数(Animal 应该是 constructor
  2. 您正在使用原型向您的 class 添加功能。为什么不以正确的方式去做(...es6+ 方式)

我会是你收到的愚蠢错误是因为 "constructor" 设置(使用 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);