问题描述
我正在学习es6 js,并找到了一种声明类并使用其方法的方法.
I am learning es6 js and found a way to declare class and use its method.
但是我想知道的一件事令人困惑.
but one thing is confusing which i want to know.
class myGender {
var gender = "male";
printMyGender(){
console.log(gender);
}
}
const gender = new myGender();
gender.printMyGender();
在上面的代码中,我遇到错误,为什么我无法在相同的班级和其他情况下访问性别变量
In the above code i am getting error why i can't access the gender variable in the same class and other scenario
class myGender {
constructor(){
this.gender = "male";
}
printMyGender(){
console.log(this.gender);
}
}
const gender = new myGender();
gender.printMyGender();
这就像魅力!.
推荐答案
在javascript中,变量和 properties 之间存在巨大差异.使用var, let, const
声明变量,然后可以使用赋值运算符(=
)向变量赋值.变量是当前作用域的一部分({
和}
之间的所有内容),它们与对象无关.属性是对象的一部分.它们不会被声明,它们会在为它们分配值之后存在,直到被删除.因此,实际上您不需要初始化它们.但是,这可能会导致一些非常有趣的行为:
In javascript there is a huge difference between variables and properties. Variables get declared using var, let, const
, then they you can assign values to them using the assignment operator (=
). Variables are part of the current scope (everything between {
and }
), they are not related to objects. Properties are part of an object. They dont get declared, they exist after a value gets assigned to them until they are deleted. So actually you don't need to initialize them. However, this can lead to some very funny behaviour:
class Counter {
increase(){
this.count += 1;
}
}
const count = new Counter;
count.increase()
console.log(count.count); //NaN
因此,在构造函数内部初始化它们是一个好习惯:
Therefore it is a good practise to initialize them inside of the constructor:
class Counter {
constructor(){
this.count = 0;
}
increase(){
this.count += 1;
}
}
要美化它并使其他语言的开发者更熟悉,类属性有一个建议(将来可能会出现):
To beautify this and make it more familar for developers from other languages, there is a proposal (it might be a feature in the future) for class properties:
class Counter {
count = 0;
increase(){
this.count += 1;
}
}
但这只是上面代码的语法糖.
however thats just syntactic sugar for the code above.
这篇关于ES6中类中的变量和函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!