簡體   English   中英

'; '嘗試創建原型函數調用時預期

[英]' ; ' expected when trying to create a prototype function call

我試圖用構造函數和原型函數創建一個簡單的Animal類,以返回Animal的名稱和描述。

到目前為止,我已經為該類創建了構造函數:

class Animal {
    Animal(name, description) {
        this.name = name;
        this.description = description;
    }
}

但是當我嘗試創建Animal原型並調用函數以返回Animal的名稱和說明時...

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

... Visual Studio代碼突出顯示Animal.prototype.message()的句點,並告訴我';' expected ';' expected

我已經呆了一個小時了,我覺得自己遺漏了一些明顯的東西,但是不管我想知道我做錯了什么。 在此先感謝您的幫助。

編輯:固定代碼錯字。

我在這里看到幾個問題。

  1. 在您的課程中,您沒有構造函數( Animal應該是constructor
  2. 您正在使用原型向類添加函數。 為什么不以正確的方式做事(... ES6 +方式)

我將收到的愚蠢錯誤是由於設置了“構造函數”(使用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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM