尝试在JavaScript中复制传递引用行为:如何正确地修改我的代码

时间:2014-04-21 18:04:26

标签: javascript

所以我有2个函数,我希望它们可以协同工作来反转div周围的对象。我使用的是图形库,因此下面会有一些不熟悉的代码片段。我想你仍然理解我想要做的事情的主旨。

function homepage_screensaver()
{
    /*
        Create Raphael object in the space of the div with id "homeandidiv"
    */
    var pappos = $("#homeanidiv").position();  
    var papx = pappos.left;
    var papy = pappos.top;
    var papheight = $("#homeanidiv").height();
    var papwidth = $("#homeanidiv").width();
    var paper = Raphael(papx, papy, papwidth, papheight);
    /*
        paper: space in which the circle will be bound
    */
    var circx = Math.floor(Math.random() * Number.MAX_VALUE) % papwidth;
    var circy = Math.floor(Math.random() * Number.MAX_VALUE) % papheight;
    /*
        circx, circy: initial positions of circle on the paper
    */
    var mycirc = paper.circle(circx, circy, 10);
    mycirc.attr("fill","#F9C624");
    var theta = Math.floor(Math.random() * Number.MAX_VALUE) % 4 + 1; 
    /*
        theta = 1 <---> object moving at a 45-degree angle
        theta = 2 <---> object moving at a 135-degree angle
        theta = 3 <---> object moving at a 225-degree angle
        theta = 4 <---> object moving at a 315 degree angle
    */
    var circwrapper = new Array(mycirc, theta);
    window.setInterval(function() { move_obj(circwrapper, papwidth, papheight);}, 100);
}

function move_obj(obwrap, backwidth, backheight)
{
     var ob = obwrap[0]; // object 
     var th = obwrap[1]; // theta, the current direction of the object
     var BB = ob.getBBox(); // bounding box for object
     var dx = 0;
     var dy = 0;
     if (BB.x >= backwidth && (th == 1 || th == 2)) 
            dx = -1;
     else if (BB.x <= 0 && (th == 3 || th == 4))
            dx = 1;

     if (BB.y >= backheight && (th == 2 || th == 3))
            dy = -1;
     else if (BB.y <= 0 && (th == 1 || th == 4))
            dy = 1;

     ob.transform("T " + dx + ", " + dy);
     if (dx == 1 && dy == -1)
        th = 1;
     else if (dx == 1 && dy == 1)
        th = 2;
     else if (dx == -1 && dy == 1)
        th = 3;
     else // (dx == -1 && dy == -1)
        th = 4;

     obwrap[0] = ob;
     obwrap[1] = th;
}

以下是我在测试页面后意识到的问题:我的函数move_obj(...)实际上并没有影响我传递给它的第一个参数。你可以在我的功能结束时看到我有

  obwrap[0] = ob;
  obwrap[1] = th;

表示我试图实际修改作为第一个参数传入的数组的值。

有没有&#34;快速修复&#34;我的问题?我宁愿不回去尝试制造全局变量。

您知道吗,我已经研究过在JS中通过引用传递的问题,并且在这里它说数组是通过引用传递的:http://orizens.com/wp/topics/javascript-arrays-passing-by-reference-or-by-value/。所以我不知道这里出了什么问题。

1 个答案:

答案 0 :(得分:1)

“移动”功能返回后,您必须重新分配。

window.setInterval(function() {
  var wrapper = [mycirc, theta];

  move_obj(wrapper, papwidth, papheight);

  mycirc = wrapper[0];
  theta = wrapper[1];
}, 100);

为数组分配新值但它只影响数组。构建数组时,您要对两个变量的值进行复制。数组槽和变量之间没有后续的隐式关系,因此对数组的更改不会影响自变量的值。

相关问题