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
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: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:
To learn more, see Top Javascript and Typescript Short-hand You must know
YOu can do do that…
use Object.assign because
this
is already an Objectby making a new Object (with braces around) ->
{ prop1, prop2, prop3, prop4 }
.I also use Whitesmiths style