5

Say I have an existing object, a, and a prototype b. I want to make a new object, c, with the values of a, but the prototype of b. Is there a nicer way than the following:

function Copy(object) {
    Object.assign(this, object);
}
Copy.prototype = Object.create(b);

var c = new Copy(a);

Edit: Is Object.setPrototypeOf better or worse than the question solution?

Jacob
  • 1,335
  • 1
  • 14
  • 28
  • 1
    Note that `Object.assign` is part of ES6 and is currently only supported in Firefox. – Alexis King Dec 18 '14 at 21:12
  • 1
    Note your `c` inherits from `Copy.prototype`, which inherits from `b`. You could make `c` inherit directly from `b` using `Copy.prototype = b` instead of `Copy.prototype = Object.create(b);`. – Oriol Dec 18 '14 at 21:29
  • [`setPrototypeOf` is the worst you could do](http://stackoverflow.com/a/23809148/1048572) – Bergi Dec 18 '14 at 21:35

1 Answers1

3

There is no need of having the Copy constructor. Just use

var c = Object.assign(Object.create(b), a);
Oriol
  • 274,082
  • 63
  • 437
  • 513