For the following code I wanted to know the reason behind this behavior in an ES6 Class:
class One {
//why the following code is not allowed.
let check = false;
const PI = 3.14;
var v = 'Hello';
//why the following code is allowed.
chk = false;
Pi = 3.14;
vv = "Hi";
}
I know I can write code like below but I wanted to know the real reason behind the above code.
class Sample {
constructor(x, y) {
this.x= x;
this.y= y;
}
}
For the following code I wanted to know the reason behind this behavior in an ES6 Class:
class One {
//why the following code is not allowed.
let check = false;
const PI = 3.14;
var v = 'Hello';
//why the following code is allowed.
chk = false;
Pi = 3.14;
vv = "Hi";
}
I know I can write code like below but I wanted to know the real reason behind the above code.
class Sample {
constructor(x, y) {
this.x= x;
this.y= y;
}
}
Share
Improve this question
edited Jan 17, 2020 at 4:47
Nick Parsons
51.2k6 gold badges57 silver badges78 bronze badges
asked Jan 17, 2020 at 4:29
yogendrayogendra
3512 gold badges5 silver badges12 bronze badges
1
-
Variables are not the same as properties. As such it would only be confusing to have the syntax of class fields use
var
,let
orconst
. – Felix Kling Commented Jan 17, 2020 at 6:26
2 Answers
Reset to default 4class One {
//why the following code is not allowed.
let check = false;
const PI = 3.14;
var v = 'Hello';
//why the following code is allowed.
chk = false;
Pi = 3.14;
vv = "Hi";
}
Actually, neither of those is legal javascript currently. The latter is an example of class fields, which is currently a stage 3 proposal, so it will eventually be legal syntax. With a transpiler, you can use that syntax right now and the transpiler will move the code into the constructor.
class One {
chk = false;
Pi = 3.14;
vv = "Hi";
}
Bees roughly:
class One {
constructor() {
this.chk = false;
this.Pi = 3.14;
this.vv = "Hi";
}
}
The trivial answer is "because that's how the class syntax is (currently) defined".
Class declarations are basically a bunch of shorthand function declarations (they just drop the "function" keyword), you can't put executable statements outside of the methods (except for proposed public and private fields, but they aren't in ECMA-262 yet) e.g.
class Foo {
// shorthand function declaration of mandatory constructor method
constructor (...) {
// Usual function syntax in here
}
// shorthand function declaration of class method
blah (...) {
// Usual function syntax in here
}
// shorthand function declaration of static method
static bar (...) {
// Usual function syntax in here
}
// etc.
}
There are ways to implement private members (JavaScript - Private members explanation?) but I think it goes away from the class syntax.