[英]Why I can not declare a variable inside an ES6 class by using let, const or var keyword but I can declare it directly?
對於以下代碼,我想知道 ES6 類中這種行為背后的原因:
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";
}
我知道我可以編寫如下代碼,但我想知道上述代碼背后的真正原因。
class Sample {
constructor(x, y) {
this.x= x;
this.y= y;
}
}
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";
}
實際上,目前這些都不是合法的 javascript。 后者是類字段的示例,目前是第 3 階段的提案,因此最終會成為合法的語法。 使用transpiler ,您現在可以使用該語法,transpiler 會將代碼移動到構造函數中。
class One {
chk = false;
Pi = 3.14;
vv = "Hi";
}
大致變成:
class One {
constructor() {
this.chk = false;
this.Pi = 3.14;
this.vv = "Hi";
}
}
簡單的答案是“因為這就是(當前)定義類語法的方式”。
類聲明基本上是一堆速記函數聲明(它們只是去掉了“function”關鍵字),您不能將可執行語句放在方法之外(建議的公共和私有字段除外,但它們不在 ECMA-262 中)還)例如
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.
}
有一些方法可以實現私有成員( JavaScript - 私有成員解釋? ),但我認為它脫離了類語法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.