One thing that really bothers me in programming languages is when the arguments passed in a constructor are directly assigned to fields in a class with matching names, like this:
class A {
constructor(a, b) {
this.a = a;
this.b = b;
etc...
}
}
To avoid this, I discovered a workaround where I could create a function that dynamically took the existing keys in a class and their corresponding arguments:
function test(values) {
Object.keys(this).map((x,i) => this[x] = values[i]);
}
class ChildObj {
a1;
a2;
constructor() {
test.call(this, arguments);
}
}
While this method works well, I wanted to further streamline it by eliminating the repetitive constructor declaration. Since I have many classes set up in a similar manner, this repetition was becoming cumbersome.
I initially considered using inheritance, but the fields belong to the child object and are not visible to the parent. Next, I attempted to modify the class's constructor dynamically based on an array of relevant classes, but altering a class's constructor directly proved to be challenging:
A.constructor = function() {
test.call(this, arguments);
}
A.prototype.constructor = function() {
test.call(this, arguments);
}
As a temporary solution, I tried defining my object as a function, yet encountered issues accessing the function parameters' names without resorting to Regex for parsing source code, which I preferred to avoid.
-----PS:-------
After some experimentation, I managed to pass the child keys to the parent by having the parent construct a clone of the child while halting recursion there:
class ParentObj {
constructor() {
if(ParentObj.constructor.in) {
return;
}
ParentObj.constructor.in = true;
let keys = Object.keys(new this.constructor);
ParentObj.constructor.in = false;
Object.keys(this).map((x,i) => this[x] = arguments[i]);
}
}
class ChildObj extends ParentObj {
a1
a2
}
console.log(new ChildObj(3, 2));
However, despite this progress, it seems something has still gone awry as the values are not being properly assigned to the resulting object.
-----END PS ---------
In conclusion, I am curious if it is feasible in Javascript to dynamically assign a constructor like this, and if not, what alternative methods exist for creating objects with simple constructors? Thank you.