Javascript - pass objects by reference

Possible duplicate:
How to save a reference to a variable in an array?

Consider the following code:

var a = 'cat'; var b = 'elephant'; var myArray = [a,b]; a = 'bear'; 

myArray [0] will still return "cat". There is a way to store links in an array instead of clones, so myArray [0] will return a "bear"?

+4
source share
5 answers

As long as I agree with everyone, saying that you should just use myArray [0] = independently, if you really want to accomplish what you are trying to accomplish, you can make sure that all the variables in the array are objects.

 var a = {animal: 'cat'}, b = {animal: 'elephant'}; var myArray = [a, b]; a.animal = 'bear'; 

myArray [0] .animal is now a bear.

+7
source

Not. Javascript does not make links this way.

+6
source

No, It is Immpossible. JavaScript does not support such links.

Only objects are saved as links. But I doubt what you want here.

+1
source

You answered your question, if you want myArray [0] to equal a bear, then set:

 myArray[0] = "bear"; 
+1
source

Even if your array contains references to objects, which makes a variable reference to a completely different object, this will not change the contents of the array.

Your code does NOT modify the object variable a. This means that the variable a refers to another object as a whole.

Like your javascript code, the following java code will not work, because, like javascript, java passes object references by value:

  Integer intOne = new Integer(1); Integer intTwo = new Integer(2); Integer[] intArray = new Integer[2]; intArray[0] = intOne; intArray[1] = intTwo; /* make intTwo refer to a completely new object */ intTwo = new Integer(45); System.out.println(intArray[1]); /* output = 2 */ 

In Java, if you modify the object the variable refers to (instead of assigning a new variable reference), you get the desired behavior.

Example:

  Thing thingOne = new Thing("funky"); Thing thingTwo = new Thing("junky"); Thing[] thingArray = new Thing [2]; thingArray[0] = thingOne; thingArray[1] = thingTwo; /* modify the object referenced by thingTwo */ thingTwo.setName("Yippee"); System.out.println(thingArray[1].getName()); /* output = Yippee */ class Thing { public Thing(String n) { name = n; } private String name; public String getName() { return name; } public void setName(String s) { name = s; } } 
+1
source

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


All Articles