3

I have a class in json format. I would like to make two instance. Right now (its pretty obvious why) when i 'make' two objects i really have 2 vars pointing to one. (b.blah = 'z' will make a.blah=='z')

How do i make a copy of an object?

var template = {
    blah: 0,
    init: function (storageObj) {
        blah = storageObj;
        return this; //problem here
    },
    func2: function (tagElement) {
    },
}

a = template.init($('form [name=data]').eq(0));
b = template.init($('form [name=data2]').eq(0));
  • Hope this posting helps. http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object – rahul Apr 20 '10 at 07:03
  • 3
    You may want to check: http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object. It was answered by John Resig himself. There should be nothing more to add! :) – Daniel Vassallo Apr 20 '10 at 07:04
  • By the way, I think that `blah = storageObj;` should be `this.blah = storageObj;`... – Steve Harrison Apr 20 '10 at 07:13

3 Answers3

2

If you want multiple instances, sounds like a constructor might do you some good.

function Template(element) {
    this.blah = element;
}

Template.prototype.func2 = function(tagElement) {
    //...
};

var a = new Template($('form [name=data]').eq(0));
var b = new Template($('form [name=data2]').eq(0));

b.func2('form');

All methods on the function prototype (Template.prototype) will be accessible from each instance, and with each instance scoped accordingly. The new keyword will run the function and then return to you a brand new object, inheritting from the prototype.

You'll no longer have the exact same object point to a and b.

seanmonstar
  • 11,284
  • 2
  • 21
  • 26
0

From the comments What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
-2
var b = {}, key;

for (key in a){

    if(a.hasOwnProperty(key)){
        b[key] = a[key];
    }

}
Vincent
  • 3,965
  • 2
  • 22
  • 30