gpt4 book ai didi

javascript - 为什么我不能在 ES6 类中使用 let、const 或 var 关键字声明变量,但可以直接声明它?

转载 作者:行者123 更新时间:2023-12-01 00:15:39 25 4
gpt4 key购买 nike

对于以下代码,我想知道 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。后者是类字段的示例,当前为 stage 3 proposal ,所以它最终将是合法的语法。与 transpiler ,您现在就可以使用该语法,转译器会将代码移动到构造函数中。

class One {
chk = false;
Pi = 3.14;
vv = "Hi";
}

大致变成:

class One {
constructor() {
this.chk = false;
this.Pi = 3.14;
this.vv = "Hi";
}
}

关于javascript - 为什么我不能在 ES6 类中使用 let、const 或 var 关键字声明变量,但可以直接声明它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com