views:

367

answers:

1

I know there is another question related to copying objects in JavaScript here, but the code they provide does not work with greasemonkey. From what I was able to trace, the code for the accepted answer dies/ stops at the line :

var temp = new obj.constructor();

Is there any way to see what went wrong ?

It's not really necessary I use the same function for the object copying, but I would like something that works. Do you know some function?

A: 

This seems to work:

var a = {
    yo: 'hello',
    do: function() {alert(this.yo + ' world');}
};

var cloneStructor = function() {};
cloneStructor.prototype = a;

var b = new cloneStructor();
a.yo = 'goodbye';
b.yo = 'what\'s up';

a.do();
b.do();
steamer25
won't this just be a reference and not a true copy?
Geo
The example I provided uses the 'new' keyword and seems to work--a and b end up with different properties. Another approach I found uses JSON.eval(JSON.stringify(cloneMe)). That might be worth trying. Otherwise, you could loop through all the properties manually and reconstruct things.
steamer25