Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object.create style with existing object

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?

like image 238
Jacob Avatar asked Oct 20 '22 20:10

Jacob


1 Answers

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

var c = Object.assign(Object.create(b), a);
like image 64
Oriol Avatar answered Oct 22 '22 10:10

Oriol