是否可以在javascript中用其他内存覆盖变量指向的内存



>假设我有一个指向该内存的变量,我实际上可以将内存更改为全新的内存,以便指向该内存的所有其他变量现在都指向新内存吗?

var foo = function(obj){
    // I want to set obj to new memory
    obj = { bar: 'foo' }
}
var boo = function(obj){
    // can change properties to new memory
    obj.too = { hoo: 'doo' }
}
var zoo = { too: { woo: 'loo' } }
// no change of memory
console.log(zoo)
foo(zoo)
console.log(zoo)
// change of memory
console.log(zoo)
boo(zoo)
console.log(zoo)

简短的回答是"是"。当您有一个对象时,对该实例的任何/所有引用都将访问该实例的当前状态。但是,请了解同一对象可以有多个实例,并且对一个实例执行的操作可能不会影响其他实例。

下面是一个更简化的示例:

var zoo = { 
  location: "San Diego"  
};
function getReference(){
  // All invocations of this function will get a reference to same instance
  return zoo; 
}
var o1 = getReference();  // reference to zoo instance is returned
var o2 = getReference();  // 2nd reference to zoo instance is returned
console.log(o1.location, o2.location); // San Diego, San Diego
o2.location = "NYC";
console.log(o1.location, o2.location); // NYC, NYC
// But, a reference to a different instance won't affect the others
var o3 = Object.create(zoo);
o3.location = "Washington DC";
console.log(o1.location, o2.location, o3.location); NYC, NYC, Washington DC

由于javascript如何将参数传递给函数(参见此答案(,答案是否定的。为了完成您想要的,我会将变量重新分配给函数的返回值,即 zoo = foo(zoo);(假设您更改foo以返回某些内容(。

您可以创建一个为您执行此操作的系统。

memorySlot1 = "one"
memorySlot2 = "two"
AssignSlot = function (memorySlot){
    return(
        {
            Slot : memorySlot,
            Content : (
                function(){
                    return (
                        window[
                            memorySlot
                        ]
                    )
                }
            )
        }
    )
}
ChangeSlotContent = function (obj,newContent){
    window[obj.Slot] =  newContent
}
console.log("______________")
var1 = AssignSlot("memorySlot1")
var2 = AssignSlot("memorySlot2")
var3 = AssignSlot("memorySlot2")
console.log(var1.Content() +" / "+ var2.Content() +" / "+ var3.Content()) // one / two / two
console.log("______________")
ChangeSlotContent(var2,"twotwo")
console.log(var1.Content() +" / "+ var2.Content() +" / "+ var3.Content()) // one / twotwo / twotwo
console.log("______________")
var1 = AssignSlot("memorySlot2")
console.log(var1.Content() +" / "+ var2.Content() +" / "+ var3.Content()) // twotwo / twotwo / twotwo

内存方面确实没有保证(它是一个实现细节(。仅仅因为您从引用中观察到一个新值并不意味着内存被覆盖(它可能只是使用新的内存空间和释放的旧空间(。变量赋值按值完成(为引用设置新值(。这意味着您不能让一个变量指向另一个变量。因此,更改任何变量都不会导致对任何其他变量的更改。

但是,可以使用任意数量的变量来保存对具有唯一键值对的唯一对象的引用。这样,变量可以访问同一对象,并且可以在保存该对象引用的任何变量中观察到对其任何属性的更改,因为每个属性对于每个对象都是唯一的。

最新更新