Javascript复制语义

时间:2013-04-01 06:28:02

标签: javascript copy semantics

以下是正常的javascript语义:

js> a={'a':{'red':12,'green':23,'blue':34}}
({a:{red:12, green:23, blue:34}})
js> b=a['a']                                                                    
({red:12, green:23, blue:34})
js>b={red:122, green:232, blue:142}                                                                        
({red:122, green:232, blue:142})
js> a
({a:{red:12, green:23, blue:34})
js>

以下是我想要的语义:

js> a={'a':{'red':12,'green':23,'blue':34}}
({a:{red:12, green:23, blue:34}})
js> b=a['a']                                                                    
({red:12, green:23, blue:34})
js>b={red:122, green:232, blue:142}                                                                        
({red:122, green:232, blue:142})
js> a
({red:122, green:232, blue:142})
js>

是否有任何简单的内在技巧可以让javascript以我的方式行事?

1 个答案:

答案 0 :(得分:0)

Javascript没有“指向引用的指针”类型。但是,您可以创建“对象的属性”类型(对象,属性名称;不能指向局部变量)。

a={'a':{'red':12,'green':23,'blue':34}}
//({a:{red:12, green:23, blue:34}})
b={obj:a, key:"a"}
b.obj[b.key]                                                             
//({red:12, green:23, blue:34})
b.obj[b.key]={red:122, green:232, blue:142}                                                                        
//({red:122, green:232, blue:142})
a
//({a:{red:122, green:232, blue:142}})

或者,您可以覆盖对象b引用:

a={'a':{'red':12,'green':23,'blue':34}}
//({a:{red:12, green:23, blue:34}})
b=a['a'] //or a.a
//({red:12, green:23, blue:34})
b.red = 122;
b.green = 232;
b.blue = 142;
b
//({red:122, green:232, blue:142})
a
//({a:{red:122, green:232, blue:142}})