Hey guys 🙋
I know, I have been doing this a lot; introducing new semantics for the of operator
But anyway...
In many OO languages, we can directly initialize properties from the parameters of the class constructor;
Here are some examples:
Typescript
class Point {
constructor(public x: number, public y: number) {
}
}
Kotlin
class Point(var x: Int, var y: Int)
Dart
class Point {
int x, y;
Point(this.x, this.y);
}
Where is JavaScript?
It's an injustice that we cannot use this shorthand!!
This proposal aims to resolve that by introducing Parameter Properties in JS
syntax:
class Person {
constructor(
name, age, gender = "male" of this,
cast = null, religion of #this,
randomID, hashSign) {
/** Equivalent to writing:
this.name = name
this.age = age
this.gender = gender
this.#religion = religion
this.#cast = cast
**/
}
}
class Person {
constructor(
randomID, hashSign,
(name, age, gender = "male") of this,
religion, cast = null of #this) {
}
}
a trailing comma like in:
constructor(
name, age, gender = "male", of this
){}
might not be considered legal
I guess an alternative way is to use decorators¿¿
It also looks way cooler than TS!..
This could also be extended to constructor functions.
function Greet(word, person of this) {
console.log(this.word + " " + this.person)
}
let greet = new Greet("Hi", "Myself")
console.log(greet.word, greet.person)
Alright,
What's your take on this?
What do you think about this proposal??
==== updated ====
On giving some thought into it I figured out that we can take a different approach and follow Kotlin's syntax.
No messing around with this
.
class Person {
constructor(var name, var #age, religion) {}
}
or
class Person {
constructor(var name, #age, religion) {}
}
we can just avoid the var in front of a private parameter property. The only downside is that we'll have to call our age parameter as #age (which doesn't seem that bad!).
This will cause the revival of the var keyword😄, which is a good thing I guess...
why not use let / const ?
well we could alternatively use let / const here. const has an added benefit of making the parameter a constant.
class Person {
constructor(const name, const #age, let religion="JavaScript") {}
}
what about destructuring?
lets see:
class Person {
constructor(
var { name, age },
var [ gender, religion ]) {}
}
or
class Person {
constructor(
let { name, age },
const [ gender, religion ]) {}
}
It's just the regular old destructuring😄