js引用类型里存放对象键值对的问题
提示
今天遇到的一个值得思考的问题,下面是问题的重现,因为写了这么久代码真没实际遇到过,记录一下。
/**
* description:test
* date: 2022/04/11/17:08:00
* author: xinyu
* version: 1.0
**/
class test<K>{
private a:test2<K>;
constructor() {
}
public add(arg:K) {
let current = new test2<K>(arg);
this.a = current;
let c = this.a;
let current2 = new test2<K>(arg);
let current3 = new test2<K>(arg);
c.b2 = current2;
c.b2.b2=current3;
//这里都还能理解,引用类型指向同一个内存地址,c变,this.a跟着变
console.log(c) //{b: '你好',b2: test2 { b: '你好', b2: test2 { b: '你好', b2: [test2] } }}
console.log(this.a) //{b: '你好',b2: test2 { b: '你好', b2: test2 { b: '你好', b2: [test2] } }}
//这里也能理解,c内存地址没有改变,里面的值改变了
c=c.b2.b2
c.b2="不好";
console.log(c); //{ b: '你好', b2: '不好' }
//到这里就感觉不正常了,不应该和c一样吗?却只变了最里面的b2
console.log(this.a);//{ b: '你好',b2: test2 { b: '你好', b2: test2 { b: '你好', b2: '不好' } }}
}
}
class test2<T>{
public b:T;
public b2:any;
constructor(element:T) {
this.b=element;
this.b2=undefined;
}
}
let test_ = new test<String>();
test_.add("你好");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
提示
c=c.b2.b2
,"="左边的c只是一个临时的变量,左边的c虽然结构变了,只是值发生了改变,内存地址没有发生改变,里面的对象的键值对的地址也没有发生改变。 c.b2=“不好”,c.b2的值发生改变,但是“.b2”仍然还是指向的原来的那一个对象的键值对的值,所以this.a里面的“.b2”的值也会发生改变。
上次更新: 2022/05/12 14:57:53