2010-06-01 18 views
3

我使用以下幾行來存儲對象的位置。javascript,jQuery:如何保存值而不是引用

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

我繼續在我的元素中移動這個對象,我想用存儲的變量恢復它以前的位置。

但是,我怕javascript是通過引用保存值,所以我失去了初始位置。我對麼 ?我該如何解決這個問題?

謝謝

回答

1

不,這些返回的值不是通過引用存儲的。如果您更改元素的topleft樣式,它不會影響您的存儲值。

javascript中的原始類型不作爲參考傳遞。

var a = "a"; 

    var b = a; 

    a = "c"; 

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

var a = 1; 

    var b = a; 

    a = 3; 

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

對象通過引用傳遞:

var a = {one:"one"}; 

    var b = a; 

    a.one = "three"; 

    alert(b.one); // alerts "three" 
    alert(a.one); // alerts "three" 
+0

不是'通過',這意味着被用作一個段,即使這樣所有參數都通過值傳遞(並且所有變量的值是一個指向像對象一樣的Primitive或Host對象的引用)。 – 2010-06-01 19:39:10

+0

@謝恩 - 謝謝你的提示。我會第一個承認我的javascript命名常常不夠完美。 – user113716 2010-06-01 19:45:26

3

在這種情況下,它不存儲任何引用,但實際值。

1

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 

通過「引用」的唯一方法是共享的變量是

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 

一個屬性,如果我們更換指着參考的變量之一發生了什麼對象目的?

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 
0

你可以嘗試jQuery.clone()方法,像這樣:

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

然後移動l左右,之後將其刪除,並重新顯示start

相關問題