skip to Main Content
class MyClass {
  constructor(prop1, prop2, prop3, prop4) {
    this.prop1 = prop1
    this.prop2 = prop2
    this.prop3 = prop3
    this.prop4 = prop4
    //prop 50 and so on
  }
}

In js, for this type of constructor assigning where all I’m doing is making instance properties with the exact same name and values as the constructor params, is there some shorthand syntax to just do this in like one line or something, or do I have to do it this way?

2

Answers


  1. There is no built-in shorthand syntax in JavaScript to assign constructor parameters to instance properties with the same name. You have to do it manually like you did in your code.

    You can use Object.assign() to copy the properties from the parameter object to the instance object. For example:

    class MyClass {
      constructor(props) {
        Object.assign(this, props);
      }
    }
    

    To learn more, see constructor – JavaScript | MDN – MDN Web Docs

    If you want more control and safety over your instance properties, you may want to use TypeScript instead of JavaScript, as it allows you to specify the types and access modifiers of your properties in the constructor shorthand syntax. For example:

    class MyClass {
      constructor(
        public prop1: string,
        private prop2: number,
        protected prop3: boolean,
        readonly prop4: any
      ) {
        // prop 50 and so on
        // no need to assign them manually
      }
    }
    

    To learn more, see Top Javascript and Typescript Short-hand You must know

    Login or Signup to reply.
  2. YOu can do do that…

    use Object.assign because this is already an Object
    by making a new Object (with braces around) -> { prop1, prop2, prop3, prop4 }.

    I also use Whitesmiths style

    class MyClass
      {
      constructor(prop1, prop2, prop3, prop4)
        {
        Object.assign(this,  { prop1, prop2, prop3, prop4 } );
        }
      showProps( )
        {
        console.log(   this.prop1, this.prop2, this.prop3, this.prop4   )
        }
      }
      
    const foo = new MyClass('a','b','c','d')
    
    foo.showProps()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search