Javascript class variables

2019-03-06 07:29发布

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.

1条回答
可以哭但决不认输i
2楼-- · 2019-03-06 08:08

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);
    }
}
查看更多
登录 后发表回答