Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - variable and function declaration in classes in ES6

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();

this works as charm !.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...