javascriptclassconstructorshorthand

Is there a js shorthand contructor parameter assignment?


class MyClass {
  constructor(prop1, prop2, prop3, prop4) {
    this.prop1 = prop1
    this.prop2 = prop2
    this.prop3 = prop3
    this.prop4 = prop4
    //prop 50 and so on (probably a design problem at this point)
  }
}

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?


Solution

  • 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