考虑以下代码:
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)
当我重置属性时,其他类可以看到更改(引用副本不会更改)。但是,当我重新赋值数组或对象时,对其他类的更改是不可见的(引用副本被更改)。如下面的输出所示:
//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
是否有办法在重赋时使更改对其他类可见?实现一种指针行为,其中的变化是"可见的"。跨多个持有引用的类?
使用getter和setter的解决方案为:
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
}
get obj() {
return this._obj
}
set obj(value) {
this._obj.pos = value.pos
this._obj.rot = value.rot
}
get position() {
return this._position
}
set position(value) {
this._position[0] = value[0]
this._position[1] = value[1]
}
}