0

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?

Community
  • 1
  • 1
Geo
  • 93,257
  • 117
  • 344
  • 520

1 Answers1

0

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
  • 9,278
  • 1
  • 33
  • 38
  • won't this just be a reference and not a true copy? – Geo Jun 24 '09 at 06:45
  • 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 Jun 24 '09 at 22:00