简体   繁体   中英

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

I am trying to create a simple Animal class with a constructor and a prototype function to return an Animal's name and description.

So far, I created the constructor for the class:

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

But when I try to create an Animal prototype and call a function to return the Animal's name and description...

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

...Visual Studio Code highlights the periods in Animal.prototype.message() and tells me ';' expected ';' expected .

I've been at this for an hour now and I feel like I'm missing something obvious, but regardless I would like to know what I'm doing incorrectly. Thanks in advance for any help.

EDIT: fixed code typos.

I see a couple of issues here.

  1. In your class, you do not have a constructor ( Animal should be constructor )
  2. You are using prototype to add a function to your class. Why not just do it the right way (...the es6+ way)

I would be the goofy error you're receiving is because of the "constructor" setup (using Animal instead of constructor ) or it's because you're doing

Animal.prototype.message() = function { ... } (should be Animal.prototype.message() = function() { ... } )

Example:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM