Is there a copy constructor in Javascript? -


i creating object in javascript. however, know using new classname() operator. want know if can make copy constructor when create new object ie var object1 = object2, member variables in object2 copied object1, , not pointer. thanks!

js not automatically generate constructors -- copy, move, or otherwise -- objects. have define them yourself.

the closest you'll come object.create, takes prototype , existing object copy properties.

to define copy constructor, can start along lines of:

function foo(other) {    if (other instanceof foo) {      this.bar = other.bar;    } else {      this.bar = other;    }  }    var = new foo(3);  var b = new foo(a);    document.getelementbyid('bar').textcontent = b.bar;
<pre id="bar"></pre>

using support deep copying recursion of same pattern:

function foo(other) {    if (other instanceof foo) {      this.bar = new bar(other.bar);    } else {      this.bar = new bar(other);    }  }    function bar(other) {    if (other instanceof bar) {      this.val = other.val;    } else {      this.val = other;    }  }    bar.prototype.increment = function () {    this.val++;  }    bar.prototype.fetch = function () {    return this.val;  }    var = new foo(3);  var b = new foo(a);  a.bar.increment();    document.getelementbyid('a').textcontent = a.bar.fetch();  document.getelementbyid('b').textcontent = b.bar.fetch();
<pre id="a"></pre>  <pre id="b"></pre>


Comments