1

I want to clone an object in Javascript. I have:

 iPath = function () { this.heading = 0; this.path = []; };
 loop = new iPath();

I know with jQuery I can do something like:

 cloneLoop = $.extend(true, {}, loop);

but than

 assert(cloneLoop instanceof iPath, "fails because loop is not an iPath");

How can i do a deep clone fulfilling last assert statement?

1
  • "deep" extension means that sub-objects will be merged as well. extend does not clone an object, it does not preserve the prototype chain either. Commented Dec 21, 2011 at 18:15

4 Answers 4

2

How about this:

cloneLoop = $.extend(true, new iPath(), loop);

...though I'm not sure if you'd want to do a deep copy. I'd think this would be better:

cloneLoop = $.extend(new iPath(), loop);
Sign up to request clarification or add additional context in comments.

Comments

1

Extend simply copies properties from one object to another. So you have to start with a pristine copy of the object you want to copy into. So use new iPath() instead of {}.

var iPath = function () { this.heading = 0; this.path = []; };
loop = new iPath();

cloneLoop = $.extend(true, new iPath(), loop);

alert(cloneLoop instanceof iPath);

Comments

1

If not supporting older browsers is an option, you should be able to use Object.create:

var cloneLoop = Object.create(loop);

Here's a demo

    function Foo() {
        this.x = 1;
        this.y = 1;
        this.blah = { f: "a", g: "b" };
    }

    var f = new Foo();
    var clone = Object.create(f);

    alert(clone instanceof Foo);
    alert(clone.blah.f);

alerts true, then a (at least on Chrome, older browsers will not support Object.create)

1 Comment

+1 Seems like setting it as the prototype object would be a good solution. For older browsers, you can use the typical Object.create patch. function create( proto ) { function f(){} f.prototype = proto; return new f; }
0

You'll need to write your own clone method:

Something along the lines of:

iPath.prototype = {
  clone: function () {
    var p;
    p = new iPath();
    $.extend(true, p, this);
    return p;
  }
}
cloneLoop = loop.clone();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.