I'm fairly new to Javascript and ran into a problem with object references. Here's a snippet of the code that reproduces the issue.
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
In the last print statement, I would've expected my_pos.x to print 69 since my_pos now refers to my_vect (or does it?). My understanding of Javascript is that only primitive values are actually copied and that object assignment maintains a reference to a single copy of the object. It looks like after the assignment of my_vect, the my_pos reference is somehow "detached" and no longer points to my_sprite.pos.
Is there some behavior of Javascript that I'm overlooking here?
开发者_如何转开发Thanks!
Your code with more comments, hope this helps
function MyVector() {
this.x = 0;
this.y = 0;
}
function MySprite() {
this.pos = new MyVector();
}
var my_sprite = new MySprite();
at this point, a new MyVector() is created and assigned to my_sprite.pos. Let call it vector#1
var my_pos = my_sprite.pos; // my_pos points to my_sprite's vector
my_pos points to vector#1 (you assign the pointer, not the data)
var my_vect = new MyVector(); // my_vector is on the heap
a new MyVector is created let's call it vector#2. Also, my_vect points to 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
the pos member of my_sprite now points to vector#2
print("my_sprite.pos.x: " + my_sprite.pos.x); // prints 69 (expected)
but my_pos still points to vector#1 as it was never re-assigned!
print("my_pos.x: " + my_pos.x); // prints 0, expected to print 69
Your not overlooking anything.
var my_sprite = new MySprite();
so here,
my_sprite.pos == new myVector();
var my_pos = my_sprite.pos; // my_pos equals that new myVector.
You never re-assign my_pos
, so it still equals that new myVector when you print it.
When assigning variables in javascript, my_pos
does not point to my_sprite.pos
since my_sprite.pos
is also a pointer, so it simple points to what my_sprite.pos
points to.
精彩评论