ed7173
ed7173

Reputation: 45

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 :

<script>
var copiedObject = Object.create(this);
x="foo";
console.log(x); // foo
</script>

and reset it to this state later on using :

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

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.

Upvotes: 2

Views: 59

Answers (1)

philipp
philipp

Reputation: 16485

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.

Upvotes: 1

Related Questions