Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clone a JavaScript class instance?

Tags:

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 stack, but could not find how to clone an instance.

function Parent(name) {
    this.name = name;
}

Parent.prototype.sayHello = function() {
    console.log('Hello my name is ' + this.name);
}

function Child(name) {
    Parent.call(this, name);
}

Child.prototype = Object.create(Parent.prototype);

var child = new Child('Billy');

var clone = $.extend(true, {}, child);
clone.name = 'Bob';

child.sayHello();
clone.sayHello();

console.log(child instanceof Child);
console.log(clone instanceof Child);

http://jsfiddle.net/39gjA/

I would prefer that the clone was deep/recursive. I.E. all properties that are objects are cloned as well.

like image 386
Petah Avatar asked Apr 15 '13 21:04

Petah


People also ask

How do you clone a set in JavaScript?

To create a shallow copy of a Set , pass the original Set as a parameter to the Set() constructor, e.g. const cloned = new Set(oldSet) . The Set() constructor takes an iterable, such as another Set , and adds all of the elements to the new Set . Copied! We used the Set() constructor to create a shallow copy of a Set .

Why do we use clone in JavaScript?

"Cloning" an object in JavaScript means creating a new object with the same properties as the original object. Objects in JavaScript are stored by reference, which means that two variables can point to the same object in memory. Modifying one object variable can impact other variables.

How many ways can you clone an object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.


1 Answers

How do I clone a JavaScript class instance?

It's hardly possible if the instance was created with heavy use of closures in the constructor function. We may never now which internal values were set, and how to reproduce such a setup. Therefore, the easiest way would be if every class offered a clone function which knows what to do.

normal jQuery extend just returns a vanilla object

Not necessarily, it returns what you passed in. Use

var clone = $.extend(true, Object.create(Object.getPrototypeOf(child)), child);

instead and your instanceof usage will work fine. Note that the true signifies a "deep" copy which may or may not be what you want. Also, $.extend will happily copy enumerable inherited properties as well, so you might need to use a more sophisticated extend function.

Or without jQuery at all, and only copying own, enumerable properties and only using a shallow copy:

var clone = Object.assign(Object.create(Object.getPrototypeOf(child)), child);

But again, not all objects will be clonable in this way, see my first point above.

like image 199
Bergi Avatar answered Oct 08 '22 21:10

Bergi