Happy Coconut
Happy Coconut

Reputation: 1063

constructor parameters in javascript

I am trying to learn about constructors in JavaScript. I was watching some tutorial where this constructor:

    class Human{
        constructor() {
          this.gender = 'male'
         
        }
        printGender(){
          console.log(this.gender);
        }
      }

was also written with shorter syntax that looked like this:

    class Human{
        gender = 'male';
      
        printGender = () =>{
          console.log(this.gender);
        }
      }

I have no problem understanding this. However, what if I have some parameters. Like this for example:

    class Human{
        constructor(gender, height) {
          this.gender = gender;
          this.height = height;
    
        }
        printGender(){
          console.log(this.gender);
        }
      }

How do I write this shorter syntax and also have parameters? I could not find anything about this question. Any help?

Upvotes: 2

Views: 8079

Answers (2)

Raja Sekar
Raja Sekar

Reputation: 2130

Upfront field declarations is just a self documentation. To set the instance value we've to use constructor method during instantiation of the class like @Tobiq said.

Upvotes: -1

Tobiq
Tobiq

Reputation: 2657

The code you wrote would be acceptable.

You could additionally do:

class Human {
    gender;
    height;

    constructor(gender, height) {
      this.gender = gender;
      this.height = height;

    }
    printGender(){
      console.log(this.gender);
    }
  }

Upvotes: 3

Related Questions