Clone instance for an independent object

I have a board class:

var board = new Board();

I want to clone a board and run a function movePieceon a new board:

var newBoard = board;
newBoard.movePiece('4a', '3b');

Because I just appoint him, both boardand newBoardwill have displaced part.

How can I clone boards to create an exact copy called newBoard, on which I can move the piece, and the original board remains the same?


I tried several different methods, for example:

Object.assign({}, orig)

and

function clone(orig) {
    let origProto = Object.getPrototypeOf(orig);
    return Object.assign(Object.create(origProto), orig);
}

from http://www.2ality.com/2014/12/es6-oop.html

+4
source share
1 answer

- , .

, , ( , ..), , , , , .

, ( ), , , , , . ( ), .

, , . , :

function CallbackList(otherObj) {
    // if another object is passed to the constructor, then initialize this
    // new instance to be a copy
    if (otherObj) {
        // copy the array from the other instance
        this.list = otherObj.list.slice(0);
    } else {
        // initalize empty list
        this.list = [];
    }
}

CallbackList.prototype = {
    addListener: function(fn) {
        this.list.push(fn);
    },
    removeListener: function(fn) {
        for (var i = this.list.length - 1; i >= 0; i--) {
           if (this.list[i] === fn) {
              this.list.splice(i, 1);
           }
        }
    },
    fire: function(/* pass args here */) {
        var args = Array.prototype.slice.call(arguments);
        this.list.forEach(function(fn) {
            fn.apply(null, args);
        });
    },
    clone: function() {
        return new CallbackList(this);
    }
};

, , , , , , , - :

  • DOM. , ( ) , , DOM DOM.
  • . , , , .
  • . , . , , , . , .
  • . , .
  • ( ). , .
+6

All Articles