Javascript, jQuery: how to save values ​​instead of links

I use the following lines to store the location of an object.

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

I sequentially move this object to my element, and I want to restore its previous position with the stored variables.

But I'm afraid that javascript stores values ​​by reference, so I'm losing my starting position. I'm right? How can i solve this?

thank

+3
source share
4 answers

No, return values ​​are not stored by reference. If you change the style topand leftelement, it will not affect your saved 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"
+1
source

, .

+3

Javascript " ".

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 “links” is to share the object, that the variable is a property

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 an object reference?

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
+1
source

You can try the jQuery.clone () method, for example:

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

then move laround, delete it and reprogram it start.

0
source

Source: https://habr.com/ru/post/1748028/


All Articles