How to clone an object in javascript? [duplicate]

2

I'm trying to pass one object per parameter of a function, but I do not want that object to change. For this I want to pass a clone parameter.

Because in javascript, by the tests I did, the object is always passed by reference.

Example:

a = {}
b = a;

b.nome = 'Wallace';

console.log(a, b); //Object {nome: "Wallace"} Object {nome: "Wallace"}

See that both objects have changed.

How can I make this assignment from b to a in javascript without keeping the references?

    
asked by anonymous 26.11.2015 / 18:00

2 answers

3

With Object.create() :

Example:

a = {}
b = Object.create(a);
b.nome = 'Gabriel';
a.nome = 'Wallace';
document.write(JSON.stringify(a), JSON.stringify(b))
    
26.11.2015 / 18:04
1

I was able to do cloning using the $.extend method of jQuery.

See:

a = {}

b = $.extend({}, a);

b.nome = 'Teste';


document.write(JSON.stringify(a), JSON.stringify(b))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
26.11.2015 / 18:07