Let's say we have a class called Person
. Person
has an age
property that is private and is initialized through the constructor
.
Like this:
class Person {
#age;
constructor(age) {
this.#age = age;
}
}
We have a lot of repetitions of age
just to do something simple. I guess it'd be good to initialize it in the parameter area as we do in Typescript.
Like this:
class Person {
constructor(#age) {}
}
We could also keep default properties there.
class Person {
constructor(#age = 18) {}
}
Thank you
.
2 Likes
Yay! Our very old parameter properties. This is a much wanted feature. Maybe it'll happen someday. Also see: this
1 Like
Of course, if you abandon that OOP stuff and defect to the Functional side, we have all the good syntax:
const Person = ( age = 18 ) => ({});
I mean, look how beautiful this is:
const Person = ( age = 18 ) => ({
announce: () => console.log( `I am ${age} years old.` ),
grow: () => age ++,
ascend: () => age = Infinity,
})
const centenarian = Person( 100 );
But, I think JS should support every programming paradigm, and decorators can't help here.
So, it's still a good idea. 
1 Like
Hello @0X-JonMichaelGalindo,
I don't agree with that. In coding, every problem has a unique solution. You can't use the same technique to solve all your problems. This is kind of like "If all you have is a hammer everything looks like a nail".
But thanks for agreeing :)
Obviously, I can't solve all my problems with real functional programming (immutability, no side effects). I just wish I could because in JS it has really beautiful syntax. That's all I meant.
OOP with classes in JavaScript (like most languages) has a boilerplate problem. Your suggestion helps.
1 Like
Sorry if I sounded rude. I was clarifying your statement for future readers because it sounded a little bit like what I said :)
1 Like