« nesto kao expert’s exchange | Super session »

Javascript new&delete and pointers

By pavic | June 7, 2006

Javascript object’s are powerfull, but there is no clear determination between shallow objects, who is deleting objects, collecting them etc.

Howewer, this all indicates that javascript is not made for large scale applications, but with today’s web 2.0 stories, it is becoming a MUST Have.

So, let’s do a littlebit of code attack to some javascript objects :)

var obj1 = new Object(); //or just {}

obj1.a = “a of obj1″;

obj1.b = new Object();

obj1.b.c = “c of b of obj1″;

//now let’s create object x

var x = {};

x = obj1;

//and here comes the dirty part:

document.writeln(”
obj1.a”+obj1.a);
document.writeln(”
obj1.a”+obj1.b);
document.writeln(”
obj1.a”+obj1.b.c);

document.writeln(”
x”+x);
document.writeln(”
x.a”+x.a);
document.writeln(”
x.b”+x.b);
document.writeln(”
x.b.c”+x.b.c);

Looks like, just assigning is a deep copy of another object ?

Let’s test it!

x.b.c = “am I deep?”
document.writeln(”
obj1.a”+obj1.b.c);
document.writeln(”
x.b.c”+x.b.c);

WOW, turns out that it’s shallow copy, DAMN!, so how can I create a deep copy?
Is there something on the net?
No wonder, googling for javascript deep object copy and javascript deep copy gives no cool results…

So, let’s create a good thing recursive object copy function!!!
Thank’s good I like recursion, and thanks to my professors at http://www.ftn.ns.ac.yu

(see attached file for tests and comments…)

Topics: PHP |

Comments are closed.