本文介绍了为什么我不能使用let,const或var关键字在ES6类中声明变量,但可以直接声明它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于以下代码,我想知道ES6类中此行为背后的原因:
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;
}
}
推荐答案
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会将代码移到构造函数中.
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";
}
大致成为:
class One {
constructor() {
this.chk = false;
this.Pi = 3.14;
this.vv = "Hi";
}
}
这篇关于为什么我不能使用let,const或var关键字在ES6类中声明变量,但可以直接声明它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!