Passing by JavaScript value

8

I have two objects: A and B:

var A={valor:0}
var B={valor:0}
A=B
A.valor=5
console.log(B.valor) // 5

I would like to know how to pass by value, since JavaScript passes by reference to objects, in this example I would like b.valor to be equal to 0;

    
asked by anonymous 15.03.2018 / 19:34

4 answers

7

Just use Object.assign(alvo, obj) , so the values of the obj properties will be made a simple copy (shallow copy). Example:

var A={valor:0, bola: 1}
var B={valor:0, bola: 2}
A = Object.assign({}, B};
A.valor=5
console.log(A) // {valor:5, bola: 2}
console.log(B) // {valor:0, bola: 2}
    
15.03.2018 / 19:43
5

For ES5 we have Object.create() , which to my knowledge, does not make an exact copy of the element but defines a prototype of the object to be cloned.

For ES6 we have, Object.assign() , which actually creates a copy ...

let A={valor:0};
let B={valor:0};
A = Object.assign({},B);
A['valor'] = 5
console.log(A) // 5
console.log(B) // 0
    
15.03.2018 / 19:51
3

Another solution in addition to Object.assign is to convert the object to JSON and deconvert to the variable that will receive the copy. The advantage over the assign is that a deep copy will be made. The disadvantage is that it only works for data types that are part of the JSON standard, ie it does not include functions and special types of objects.

Example:

var original = {a: 1, b: 2};
var copia = JSON.parse(JSON.strinfigy(original)); 
    
15.03.2018 / 19:58
1

For reference, my response is similar to that of @Adriano Martins using the # 1 (ES6), but passing the direct value into the method:

var A={}
var B={valor:0, valor2:1, valor3:2}
A = Object.assign({}, B, {valor: 5})
console.log(A.valor,B.valor) // retorna 5 0

1 Not supported in IE.

A form with greater browser compatibility would build a clone object of B with new Object() :

var A={}
var B={valor:0, valor2:1, valor3:2}
var novoB = new Object(); // crio o objeto
for(var vals in B){ // importo os valores de B para novoB
   if (B.hasOwnProperty(vals)) novoB[vals] = B[vals];
}
A=B // faço uma cópia de B para A
B=novoB // substituo B por novoB
novoB = null // esvazio o objeto que não servirá mais
A.valor=5, A.valor2=4 // altero os valores de A sem alterar B
console.log(A.valor,B.valor) // retorna: 5 0
console.log(A,B) // retorna A com valores alterados e B intacto
    
15.03.2018 / 20:41