Javascript pass by value

Asked

Viewed 158 times

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

would like to know how to pass by value, because Javascript passes by reference the objects, in this example would like b.valor equals 0;

  • This example is kind of confusing, why declare A and B as distinct objects if you do A=B after? What would be the case of real use? Perhaps there is another solution that does not require copying the object (which is the only way to escape the reference).

  • my real example has many instances, this example is not really for real use, but it happens exactly the error I want to solve, I would like to perform the passage by value, and not another solution

4 answers

6


Just use Object.assign(alvo, obj), so the values of 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}

5

To ES5 we have Object.create(), which, as far as I know, does not make an exact copy of the element but rather defines a prototype of the object to be cloned.

To ES6 we have, Object.assign(), that 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

3

Other solution besides the Object.assign is to convert the object to JSON and disconnect it into the variable that will receive the copy. The advantage over the assign is that a deep copy will be made. The downside is that it only works for the data types that are part of the JSON standard, i.e., it does not include functions and special types of objects.

Example:

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

1

For reference, my answer is similar to @Adriano Martins using the method Object.assign()1 (ES6), but passing the direct value in 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 way with greater compatibility between browsers would be to build an object clone 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.