我是 Javascript 的新手,遇到了对象引用问题。下面是重现该问题的代码片段。
function MyVector() {
this.x = 0;
this.y = 0;
}
function MySprite() {
this.pos = new MyVector();
}
var my_sprite = new MySprite();
var my_pos = my_sprite.pos; // my_pos points to my_sprite's vector
var my_vect = new MyVector(); // my_vector is on the heap
my_vect.x = 69;
print("my_pos.x: " + my_pos.x); // prints 0 (expected)
my_sprite.pos = my_vect; // should point to my_vect
print("my_sprite.pos.x: " + my_sprite.pos.x); // prints 69 (expected)
print("my_pos.x: " + my_pos.x); // prints 0, expected to print 69
在最后的打印语句中,我希望 my_pos.x 打印 69,因为 my_pos 现在指的是 my_vect(或者是吗?)。我对 Javascript 的理解是,实际上只有原始值被复制,并且对象分配维护对对象的单个副本的引用。看起来在分配 my_vect 之后,my_pos 引用以某种方式“分离”并且不再指向 my_sprite.pos。
我在这里忽略了某些 Javascript 行为吗?
谢谢!
最佳答案
您的代码有更多注释,希望对您有所帮助
function MyVector() {
this.x = 0;
this.y = 0;
}
function MySprite() {
this.pos = new MyVector();
}
var my_sprite = new MySprite();
此时,创建了一个新的 MyVector() 并将其分配给 my_sprite.pos。我们称它为向量#1
var my_pos = my_sprite.pos; // my_pos points to my_sprite's vector
my_pos 指向 vector#1(你分配指针,而不是数据)
var my_vect = new MyVector(); // my_vector is on the heap
创建了一个新的 MyVector,我们称它为 vector#2。此外,my_vect 指向 vector#2
my_vect.x = 69;
print("my_pos.x: " + my_pos.x); // prints 0 (expected)
my_sprite.pos = my_vect; // should point to my_vect
my_sprite 的 pos 成员现在指向 vector#2
print("my_sprite.pos.x: " + my_sprite.pos.x); // prints 69 (expected)
但 my_pos 仍然指向 vector#1,因为它从未被重新分配!
print("my_pos.x: " + my_pos.x); // prints 0, expected to print 69
关于Javascript浅拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5794384/