Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this object being passed by reference when assigning something else to it?

I know that in JS, objects are passed by reference, for example:

function test(obj) {     obj.name = 'new name'; }  var my_obj = { name: 'foo' }; test(my_obj); alert(my_obj.name); // new name 

But why doesn't the below work:

function test(obj) {     obj = {}; }  var my_obj = { name: 'foo' }; test(my_obj); alert(my_obj.name); // foo 

I have set the object to {} (empty) but it still says foo.

Can any one explain the logic behind this?

like image 304
Dev555 Avatar asked Feb 24 '12 21:02

Dev555


People also ask

How will you pass object to the function by reference?

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.

Are objects passed by reference by default C++?

C++ always gives you the choice: All types T (except arrays, see below) can be passed by value by making the parameter type T , and passed by reference by making the parameter type T & , reference-to- T .

Are objects assigned by reference?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

Are objects in JavaScript passed by reference?

In Javascript objects and arrays are passed by reference.


1 Answers

If you are familiar with pointers, that's an analogy you can take. You're actually passing a pointer, so obj.someProperty would dereference to that property and actually override that, while merely overriding obj would kill off the pointer and not overwrite the object.

like image 133
Alexander Varwijk Avatar answered Oct 20 '22 00:10

Alexander Varwijk