How do I clone a JavaScript class instance?
I tried the normal jQuery extend, but that just returns a vanilla object. I have looked through many other answers on sta
I'd be interested to see someone benchmark this method against other approaches to cloning class instances in JavaScript that use native JavaScript.
// Defining a class
function MyClass(args) {
this.foo = "bar";
}
// Avoid duplicate instances of class methods in RAM by adding them to the class prototype like this
MyClass.prototype.method = method;
MyClass.prototype.clone = clone;
// Define what your methods do
function method() {
console.log(this.foo);
}
function clone() {
var classScope = this;
// Get the prototype of your class. This will create an object that has one key for every method in your class. I'm not sure if this will go up the prototype chain if you have subclasses. Someone ought to edit this answer to clarify that.
var miniMe = Object.getPrototypeOf(this);
// Iterate the properties of your class--all the internal key-value pairs that do get duplicated in RAM each time you instantiate the class.
Object.keys(this).forEach(iterate);
function iterate(key, index, list) {
// Add each property to your clone
miniMe[key] = classScope[key];
}
// Return the clone
return miniMe;
}
// Instantiate your class
var me = new MyClass();
// Clone it
var miniMe = me.clone();
// Run some tests
Object.keys(Object.getPrototypeOf(me)).forEach(iterate);
Object.keys(me).forEach(iterate);
function iterate(property, index, list) {
if (!miniMe.hasOwnProperty(property))
throw new Error("miniMe does not have property " + property);
}
// Change the value of miniMe.foo and make sure it didn't impact the value of me.foo
miniMe.foo = "baz";
if (me.foo === miniMe.foo)
throw new Error("me.foo should not equal miniMe.foo, because we changed its value");