Looking to access an object's property by reference? See the code snippet below;
class Point{
x:number;
y:number;
constructor(x,y)
{
this.x=x;
this.y=y;
}
}
const a = { first: new Point(8,9), second: new Point(10,12) };
let someBool = true;
function modifyProperty(a) {
let c = someBool? a.first: a.second;
let newPoint = new Point(0,0);
c = newPoint; // Doesn't work
someBool = !someBool;
}
modifyProperty(a);
console.log(a.first);
In this scenario, alternating between modifying 'a' properties when calling modifyProperty() doesn't quite work as expected.
One possible solution involves making the properties in 'a' objects themselves. Essentially like so:
const a = { first: {value: new Point(8,9)}, second: {value: new Point(10,12)} };
This allows you to assign a new value to 'c' using c.value = newPoint
. However, this workaround is not ideal given that it would need to be done for each property within an object.
Is there a better way to achieve pass-by-reference for accessing these properties? While JavaScript only supports this for objects and arrays, what about instances of classes?
Noting how Babel treats classes as functions in standard Javascript conversion, could utilizing their object callable nature provide a potential solution?