I am creating an object in javascript. However, I know that I am using the new className() operator. I want to know if I can make a copy constructor so when I create a new object ie var object1 = object2, only the member variables in object2 are copied into object1, and not the pointer. Thanks!
Asked
Active
Viewed 1.1k times
1
-
Related: [Most elegant way to clone a JavaScript object](http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object) / [What is the most efficient way to clone an object?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – Jonathan Lonowski May 08 '15 at 15:10
-
In the manner you described, no. For other options, use the search, this question has many duplicates. – Etheryte May 08 '15 at 15:10
-
if members are objects do you want deep or shallow copy? – webduvet May 08 '15 at 15:21
1 Answers
6
JS does not automatically generate constructors -- copy, move, or otherwise -- for any objects. You have to define them yourself.
The closest you'll come is something like Object.create
, which takes a prototype and an existing object to copy the properties.
To define a copy constructor, you can start with something along the lines of:
function Foo(other) {
if (other instanceof Foo) {
this.bar = other.bar;
} else {
this.bar = other;
}
}
var a = new Foo(3);
var b = new Foo(a);
document.getElementById('bar').textContent = b.bar;
<pre id="bar"></pre>
Using this to support deep copying is just a recursion of the 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 a = 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>

ssube
- 47,010
- 7
- 103
- 140