2

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?

4
  • Please avoid the term "ES7" in this context. ES7 came out in 2016 and does not include these features. These are just experimental proposals. Commented Apr 14, 2019 at 0:50
  • No problem, replace it with experimental proposals Commented Apr 14, 2019 at 0:51
  • 1
    If whatever you were reading referred to this syntax as "ES7", you should probably stop reading it and find a different source. This is part of a TC39 proposal currently in progress. Commented Apr 14, 2019 at 1:02
  • Thanks a lot for the guidance. Much appreciated! Commented Apr 14, 2019 at 1:11

2 Answers 2

3

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);
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but my question is how can I do it without the constructor like second example, but with parameters.
You can't... That's the only way to your constructor's arguments. Unless, you have a super class that sets an argument to a property - i.e. within a React.Component you can use this.props within your subclass to set a property, because the super Component class assigned the props argument to the props property.
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.