How to make a copy of an object? Javascript

I have a class in json format. I would like to make two examples. Right now (it’s pretty obvious why), when I create two objects, I really have 2 vars pointing to one. (b.blah = 'z' will do a.blah == 'z')

How to 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));
+3
source share
3 answers

If you need multiple instances, sounds like a constructor can benefit you.

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');

(Template.prototype) . , , .

a b.

+2
var b = {}, key;

for (key in a){

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

}
-2
source

Source: https://habr.com/ru/post/1741895/


All Articles