tags:

views:

103

answers:

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));
A: 
var b = {}, key;

for (key in a){

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

}
Vincent
Ouch, seems like I misunderstood the question...seanmonstar's answer is the way to go!
Vincent
you did answer the title of the question. i just felt the constructor pattern fit better for his purposes
seanmonstar
+2  A: 

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