2

Tengo un objeto tablero que es el siguiente:

   function Tablero(){

    this.mapa = 
                 [[0,0,0,0,0,0],
                  [0,0,0,0,0,0],
                  [0,0,0,0,0,0],
                  [0,0,0,0,0,0],
                  [0,0,0,0,0,0],
                  [0,0,0,0,0,0]];


    this.habilitarPos = function(){
        var coorCompleta = this.disponible().split("-");        
        return [coorCompleta[0],coorCompleta[1]];       
    };

    this.disponible = function(){ 
            var nuevoDisp = []; //retorna un arreglo de las posiciones 
            this.mapa.forEach(function(fila,indexf) {
                fila.forEach(function(colum,indexc) {
                    if(colum === 0){
                        nuevoDisp.push(indexf+"-"+indexc);
                    }
                });
            });
            //retorna una posicion cualquiera del arreglo de posiciones vacias
            return nuevoDisp[Math.floor((Math.random() * nuevoDisp.length))]

    };  

    this.actualizar = function(elemento){
        if(this.mapa[elemento.posfila][elemento.poscol] !== 0){
            if(this.mapa[elemento.posfila][elemento.poscol].tipo == 3){
                this.mapa[elemento.posfila][elemento.poscol] =  elemento;           
            }else{
                this.mapa[elemento.posfila][elemento.poscol] =  4;
            }
        }else{
            this.mapa[elemento.posfila][elemento.poscol] =  elemento;
        }
    };

    this.quitarCaballo = function(elemento){
         if(this.mapa[elemento.posfila][elemento.poscol] == 4){ 
            if(elemento.tipo == 1){
                this.mapa[elemento.posfila][elemento.poscol] =  maquina;
            }else if(elemento.tipo == 2){
                this.mapa[elemento.posfila][elemento.poscol] =  usuario;
            }   
         }else{
             this.mapa[elemento.posfila][elemento.poscol] =  0;
         }
    };

    this.pintarme = function(){

        this.mapa.forEach(function(fila,indexf) { //recorrer mi mapa y pintar 0 = vacio, 4 = usuario y maquina, objeto = objeto
                fila.forEach(function(elemento,indexc){
                    if(elemento !== 0 && elemento !== 4){
                        switch(elemento.tipo) {
                                case 1://usuario
                                    $("#"+elemento.posfila+elemento.poscol).html("<img src='img/usuario.png' width='50px' height='50px' />");
                                    break;
                                case 2://maquina
                                    $("#"+elemento.posfila+elemento.poscol).html("<img src='img/maquina.png' width='50px' height='50px' />");
                                    break;                              
                                case 3://manzana
                                    $("#"+elemento.posfila+elemento.poscol).html("<img src='img/manzana.png' width='50px' height='50px' />");
                                    break;  
                                default:
                                    $("#"+indexf+indexc).html("");
                            } 
                    }else if(elemento == 4){
                                $("#"+indexf+indexc).html("<img src='img/UM.png' width='50px' height='50px' />");
                    }else{
                        $("#"+indexf+indexc).html("");
                    }
                });
            });
    }

}

al crearlo :

var tablero_Original = new Tablero();

despues agrego un objeto en el arreglo que esta en this.mapa, el objeto que ingreso es el siguente:

function Caballo(usu) {
    this.posinicial = tablero.habilitarPos();
    this.posfila = 0; //this.posinicial[0];
    this.poscol = 0; //this.posinicial[1];
    this.manzanas = 0;
    this.tipo = usu; // 1 usuario, 2 maquina
    this.dondeSaltar = function(){
        return movimientosValidos(parseInt(this.posfila),parseInt(this.poscol));
    };
    this.setPos = function(pf,pc) {     
            this.poscol = pc;
            this.posfila = pf;
        };
}


maquina = new Caballo(2);// inicio la maquina   
tablero_Original.actualizar(maquina); //ingreso la maquina en el tablero

AHORA, deseo crear un nuevo tablero que este exactamente igual al original

var tableroClon =  new Tablero();
tableroClon.mapa = tablero_Original.mapa;

el problema es que cuando hago eso y quiero agregar al tableroClon un objeto (es decir queda con el objeto del tablero original y otro que agrego nuevo):

usuario = new Caballo(1);// inicio el usuario   
tableroClon.actualizar(usuario); //ingreso el usuario en el tablero

Se me actualizan los dos tableros, es decir los dos tableros quedan igual.

1 respuesta 1

1

Debes clonar el objeto, cuando haces:

tableroClon.mapa = tablero_Original.mapa;

Estas haciendo referencia al mismo objeto almacenado en memoria, por lo que los cambios que realices en uno se verán reflejados en el otro.

La solucion:

function copiarObjeto(objeto) {
    return JSON.parse(JSON.stringify(objeto));
}

tableroClon.mapa = copiarObjeto(tablero_Original.mapa);

Para información más detallada: http://www.zsoltnagy.eu/cloning-objects-in-javascript/

Básicamente convierte el objeto a JSON y depués lo vuelve a convertir, así desreferencia en memoria todo lo referenciado. Mira el articulo, es bastante interesante.

2

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.