ed7173 ed7173 - 1 month ago 4x
Javascript Question

Reinstate cloned object in JavaScript

I would like to store the initial state of the "this" (global) scope as shown in the pseudo code below :

var copiedObject = Object.create(this);
console.log(x); // foo

and reset it to this state later on using :

this = Object.create(copiedObject);
console.log(x); // undefined since it's a copy before x was assigned

Is this the correct way of cloning this and using that clone to replace the original later on ? I would like to do this instead of "refreshing" the page of my HTML5/JavaScript app and purge
newly added functions from AJAX.


In the code you have posted, you are making a shallow copy of the object. So all the Properties of o1 are copied by reference to o2, if these are complex types (Objects). What means:

 var o1 = { a: { b: 1 } },
     o2 = Object.create(o1);

o1.a.b = 10;
console.log(o2.a.b) // 10

What you need to do is deep copy (SO), but as you might see, this will lead you down a very deep rabbit hole.