admin管理员组

文章数量:1296331

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!

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!

Share Improve this question asked May 8, 2015 at 15:08 ExtremelySeriousChickenExtremelySeriousChicken 4182 gold badges5 silver badges16 bronze badges 3
  • Related: Most elegant way to clone a JavaScript object / What is the most efficient way to clone an object? – Jonathan Lonowski Commented May 8, 2015 at 15:10
  • In the manner you described, no. For other options, use the search, this question has many duplicates. – Etheryte Commented May 8, 2015 at 15:10
  • if members are objects do you want deep or shallow copy? – webduvet Commented May 8, 2015 at 15:21
Add a ment  | 

1 Answer 1

Reset to default 7

JS does not automatically generate constructors -- copy, move, or otherwise -- for any objects. You have to define them yourself.

The closest you'll e 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>

本文标签: Is there a copy constructor in JavascriptStack Overflow