Issue
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
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.
Answered By - CertainPerformance Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.