Anton Stafeyev
Anton Stafeyev

Reputation: 2859

How to declare a public field within an ES6-style class?

I have encountered an error while trying to declare a variable inside of a JavaScript class. Here is an example of code.

class BaseContainer {
  constructor(parent) {
    this.Shell = document.createElement("DIV");
    parent.appendChild(this.Shell);
  }
  this.SomeVar = 1;
};

It gives me an error.

Upvotes: 0

Views: 160

Answers (2)

Tamil Prakash
Tamil Prakash

Reputation: 106

Define variable without this keyword,

class BaseContainer {
  SomeVar = 1;
  constructor(parent){
    this.Shell = document.createElement("div");
    parent.appendChild(this.Shell);
  }
}

Upvotes: 2

Bergi
Bergi

Reputation: 665276

Well, you cannot declare variables inside a class. Put it in the constructor if you want to create a property. Also, you must not put semicolons after method declarations (including the constructor).

class BaseContainer {
    constructor(parent) {
        this.someVar = 1;
        this.shell = document.createElement("div");
        parent.appendChild(this.shell);
    }
}

Upvotes: 2

Related Questions