Cloned objects and supporting internal functions

I am trying to do the following:

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; } 

Now I can do the following simply:

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

The problem starts when I try to use autoAdvance :

 e1.autoAdvance(); 

will launch autoAdvance for all cloned element instances. I'm sure this is probably pretty trivial, but I just don't know how to reference the parent object inside my autoAdvance function in such a way that it clones correctly and only affects the instance. Thanks!

EDIT:

This is the actual code I'm using:

 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; } 

I create two players:

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

But what happens when I use:

 player1.loop(); 

Activation for player2 will also begin to play.

+4
source share
1 answer

I suggest you start using the "class" in JavaScript. This is more or less a function.

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

This does not answer your question, but it is an alternative way to write code cleaner and better.

0
source

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


All Articles