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?
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.
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 .
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.
In Javascript objects and arrays are passed by reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With