是否有可能通过javascript中的某些其他内存覆盖变量指向的内存?

问题描述 投票:0回答:4

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

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)
javascript pointers memory
4个回答
1
投票

简短的回答是“是”。如果有对象,则对该实例的任何/所有引用都将访问该实例的当前状态。但是,要了解您可以拥有同一对象的许多实例,并且您对一个实例所做的操作可能不会影响其他实例。

这是一个更简化的例子:

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

1
投票

由于javascript如何将参数传递给函数(请参阅this answer),答案是否定的。为了实现你想要的,我会将变量重新分配给函数的返回值,即zoo = foo(zoo);(假设你改变foo以返回一些东西)。


1
投票

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

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

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.