克隆对象和函数内部引用

时间:2012-02-14 12:19:57

标签: javascript jquery object

我正在尝试执行以下操作:

var element = {};
element.attrA = 'A';
element.attrB = 1;
element.autoAdvance = function(){
   var that = this;
   setInterval(function(){
     that.attrB++;
   },100);
}
element.instance = function(){
   var clone = $.extend(true, {}, this);
   return clone;
}

现在我可以做到以下几点:

var e1 = element.instance();
var e2 = element.instance();
e1.attrA = 'not e2s business';
e2.attrA = 'not e1s attrA';

当我尝试使用autoAdvance时,麻烦就开始了:

e1.autoAdvance();

将为element的所有克隆“实例”启动autoAdvance。我确信这可能相当简单,但我只是不知道如何在我的autoAdvance - 函数中引用父对象,以便它被正确克隆并且只影响实例。谢谢!

修改

这是我正在使用的实际代码:

var player = {}; 
player.sprites = {};
player.sprites.back = ['img/playerback_01.png','img/playerback_02.png','img/playerback_03.png'];
player.sprites.head = ['img/playerhead_01.png','img/playerhead_02.png','img/playerhead_03.png'];
player.back = new Image();
player.back.src = player.sprites.back[0];
player.head = new Image();
player.head.src = player.sprites.head[0];
player.loop = function(){
    var that = this;
    var loop = setInterval(function(){
            //remove the [0] state from the sprite array and add it at [2]
        var state = that.sprites.head.shift();
        that.sprites.head.push(state);
        state = that.sprites.back.shift();
        that.sprites.back.push(state);
        that.back.src = that.sprites.back[0];
        that.head.src = that.sprites.head[0];
        }, 100);
}
player.x = 0;
player.y = 0;
player.instance = function(){
   var clone = $.extend(true, {}, this);
   return clone;
}

我产生两个玩家:

var player1 = player.instance();
var player2 = player.instance();

但发生的事情是我使用时:

player1.loop();

player2的动画也将开始播放。

1 个答案:

答案 0 :(得分:0)

我建议你在JavaScript中开始使用“class”。它们或多或少都是一种功能。

function Player(){
this.sprites={};
......
}
Player.prototype.loop=function(){
....
}
var player1=new Player();
var player2=new Player();
player1.loop();
player2.loop();// this should work better

它并没有真正回答您的问题,但它是以更清洁,更好的方式编写代码的另一种方法。