views:

55

answers:

4

hi,

I'm using the following lines to store the location of an object.

var lightboxTop = $('#lightbox').css('top');
var lightboxLeft = $('#lightbox').css('left');

I'm successively moving this object in my element, and I want to restore it previous position with the stored variables.

But, I'm afraid javascript is saving the values by reference so I lose the initial positions. Am I correct ? How can I solve this ?

thanks

+3  A: 

In this case it's not storing any reference, but the actual value.

CharlesLeaf
+1  A: 

No, those values returned are not stored by reference. If you change the top and left style of the element, it will not affect your stored values.

Primitive types in javascript are not passed by reference.

    var a = "a";

    var b = a;

    a = "c";

    alert(b);  // alerts "a"
    alert(a); // alerts "c"

or

    var a = 1;

    var b = a;

    a = 3;

    alert(b);  // alerts "1"
    alert(a); // alerts "3"

Objects are passed by reference:

    var a = {one:"one"};

    var b = a;

    a.one = "three";

    alert(b.one);  // alerts "three"
    alert(a.one); // alerts "three"
patrick dw
Not 'passed', that would imply being used as an argment, and even then all arguments are passed by value (and the value of all variables is a reference pointing to to either a Primitive or a Host Object like object).
Sean Kinsey
@Sean - Thanks for the note. I'll be the first to admit that my javascript nomenclature is often less than perfect.
patrick dw
+1  A: 

Javascript has no support for 'by reference'.

var a = 1; // a is 1
var b = a; // b is set to the value of a, that is, 1
a = 2; // a is set to 2, b is still 1

The only way to pass 'references' is to share the object that the variable is a property of

var props = {};
props.a = 1;
var newprops = props; // props === newprops = true, both variables point to the same reference
newprops.a // is 1
props.a = 3;
newprops.a // is 3

And what happens if we replace one of the variables pointing to the reference to the object?

props = {}; // props === newprops = true, props is set to a NEW object, newprops still points to the old one
props.a = 2; // is 2
newprops.a; // is still 3
Sean Kinsey
A: 

You could try jQuery.clone() method, like so:

var l = $('#lightbox');
var start = l.clone().hide();

then move l around, remove it afterwards and redisplay start.

cji