Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare the class meber variable in Javascript ES6?

class MyDemo{
  let x =5;
}

We can get an error. But when we remove the let keyword, it would be correct. I want to know why this happend.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let is used to create a new standalone identifier – a variable name. Directly inside a class, assignment is using class instance field syntax to assign to a property of the instance.

That is, this

class MyDemo {
  x = 5;
}

means you can then do

const demo = new MyDemo();
console.log(demo.x); // logs 5

x is not a new identifier with a particular block scope – rather, it’s a property of the object, so it wouldn’t have made sense if the syntax required (or even permitted) them to be preceded by let (or const).

A property of an object, with a particular configuration (getter, setter, configurable, writable) is a pretty different concept from a standalone identifier (declared with const, let, or var). Mixing the two, like your code does, would just have been too misleading.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading