考慮以下程式碼:
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)
當我重置屬性時,其他類別可以看到更改(引用副本未更改)。但是當我重新分配數組或物件時,其他類別看不到更改(引用副本已更改)。如下面的輸出所示:
//重置 FITEM [ 3, 4 ] { pos: [ 4, 5, 6 ], rot: [ 7, 8, 9 ] } OTHER [ 3, 4 ] { pos: [ 4, 5, 6 ], rot: [ 7, 8, 9 ] } // 更改对其他类可见 //重新分配 FITEM [ 1, 2 ] { pos: [ 1, 2, 3 ], rot: [ 4, 5, 6 ] } OTHER [ 3, 4 ] { pos: [ 4, 5, 6 ], rot: [ 7, 8, 9 ] } // 更改对其他类不可见
有沒有辦法使更改在重新分配時對其他類別可見,以實現一種指標行為,使更改在許多持有引用的類別之間是「可見」的?
使用getter和setter的解決方案如下: