I am attempting to clone an object in Javascript. I have made my own \'class\' that has prototype functions.
My Problem: When I clone an object, the
I would instance the clone object using the constructor of the object to be cloned:
var copy = {};
will be
var copy = new obj.constructor();
It is a quick response and I haven't pondered about drawbacks of such solution (I'm thinking of heavy constructor) but, at a first glance it should work (I wouldn't mention (or resort to) esoteric methods as __proto__).
Update:
you should resort to object.create to solve this problem.
var copy = {};
will be
var copy = Object.create(obj.constructor.prototype);
In this way the original constructor is not called to create the object (think of a constructor that does an lengthy ajax call to retrieve data from server) as Object.create is equivalent to
Object.create = function (proto) {
function F() {}
F.prototype = proto;
return new F();
};
And you can use this code if the javascript engine you are using does not support this function (it was added to the ecmascript 5 specs)