You've asked if there's anything native in JavaScript itself that does that. The answer is no, JavaScript does not currently support that. You have to write the property assignments yourself (either the way you have in your first code block, or in a constructor
definition in a class
).
Looking beyond JavaScript itself to similar languages that can compile to JavaScript, TypeScript has Parameter properties as follows:
class Octopus {
constructor(readonly name: string) {}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name;
Notice how we [...] just use the shortened
readonly name: string
parameter on the constructor to create and
initialize the name
member. We’ve consolidated the declarations and
assignment into one location.
Parameter properties are declared by prefixing a constructor parameter
with an accessibility modifier or readonly
, or both. Using private
for
a parameter property declares and initializes a private member;
likewise, the same is done for public
, protected
, and readonly
.