Consider this code:
class ClassA {
constructor(positon, obj) {
this.position = positon
this.obj = obj
}
}
class ClassB {
constructor() {
this.position = [1, 2]
this.obj = {
pos: [1, 2, 3],
rot: [4, 5, 6]
}
this.classAInstance = new ClassA(this.position , this.obj)
}
}
class ClassC {
constructor(position, obj) {
this.obj = obj
this.position = position
}
reassignObj(){
this.obj = {
pos: [4, 5, 6],
rot: [7, 8, 9]
}
}
resetObj() {
this.obj.pos = [4, 5, 6],
this.obj.rot = [7, 8, 9]
}
reassignPosition() {
this.position = [3, 4]
}
resetPosition() {
this.position[0] = 3
this.position[1] = 4
}
}
let fItem = new ClassB()
let other = new ClassC(fItem.position, fItem.obj)
other.resetObj()
other.resetPosition()
console.log('RE-SETTING')
console.log('FITEM', fItem.position, fItem.obj)
console.log('OTHER', other.position, other.obj)
fItem = new ClassB()
other = new ClassC(fItem.position, fItem.obj)
other.reassignObj()
other.reassignPosition()
console.log('RE-ASSINGNING')
console.log('FITEM', fItem.position, fItem.obj)
console.log('OTHER', other.position, other.obj)
When I reset the properties, changes are visible by other classes (reference copy is not changed). But when I reassign the array or the object, changes are not visible to the rest of the classes (reference copy is changed). As mentioned in the output below:
//RESETTING
FITEM [ 3, 4 ] { pos: [ 4, 5, 6 ], rot: [ 7, 8, 9 ] }
OTHER [ 3, 4 ] { pos: [ 4, 5, 6 ], rot: [ 7, 8, 9 ] } // changes visible to other
//REASSIGNING
FITEM [ 1, 2 ] { pos: [ 1, 2, 3 ], rot: [ 4, 5, 6 ] }
OTHER [ 3, 4 ] { pos: [ 4, 5, 6 ], rot: [ 7, 8, 9 ] } // changes not visible to other
Is there any way to make changes visible to other classes on reassignment to achieve kind o a pointer behaviour where changes are "visible" across many classes holding the reference?