1

以下是正常的 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 以我的方式行事?

4

1 回答 1

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}})
于 2013-04-01T06:41:44.687 回答