Cloning

A clone is an object that shares the properties of the object from which it was cloned, but is modified independently from the original object, with changes made to the clone never affecting the original.

A clone of an object is essentially a JS object wrapping the original object — the clonee. The clone is initially identical to the clonee but is not the same object. Traps cascade to traps on the clonee, puts act on the clone, and reads fallback to the clonee only when the property is not in the keyset of the clone.

Creating Clones

Clones are created using the vexi.js.clone() function.

You may get the original object using vexi.js.unclone() function. It will always get the original object and never return a clone.

You may created multiple clones of an object. You may create clones of clones. Clones can be created and discarded without affecting the original object directly.

A clone is a different object to its clonee, so the following is always true:

 vexi.js.clone(clonee) != clonee;

All non-primitive types are cloneable, including immutables.

Clone Behaviour

General behaviour:

Keyword specific behaviour:

Consider:

 var clonee = { a:3, b:5 };
 var clone = vexi.js.clone(clonee);

 // true
 3 == clonee.a == clone.a;

 // still true after put to clone
 clone.a = 2;
 2 == clonee.a == clone.a;

 // put to clonee.a alters this
 clonee.a = 1;
 1 == clone.a;
 2 == clonee.a;
 clonee.a != clone.a;

 // non-cascading traps on clone do not affect clonee
 clone.b ++= function(v) { return; }
 clone.b ++= function() { return 0; }

 // these puts are not equivalent
 clone.b = 2;  // clone.b == 0, clonee.b == 5
 clonee.b = 2; // clone.b == 0, clonee.b == 2

 // these reads are not equivalent
 var r1 = clone.b;  // r1==0
 var r2 = clonee.b; // r2==2

 // write trap on clonee affects clone put
 clonee.c ++= function(v) { cascade = 2*v; }
 clone.c = 2;
 clone.c == 4; // true
 clonee.c = 3;
 clonee.c == 6; // true

 


Copyright © 2011 The Vexi Project (vexi.sourceforge.net)