Reputation: 300
Consider this chunk of code, which is a basic example of passing an argument by value (here it's an object, which is passed by value):
function setName(obj) {
obj.name = "Pork";
obj = new Object();
obj.name = "Chicken";
}
var person = new Object();
setName(person);
alert(person.name);
The output of this code is "Pork" (obviously), but what I'm trying to understand is why the new object created in the setName function does not overwrite the value stored in obj. Instead, this apparently creates a pointer to a local object, which is destroyed when the function execution ends.
Upvotes: 0
Views: 242
Reputation: 571
when you are calling setName
function ,you are passing reference of person
to it.now both obj
and person
holds reference to the object. obj
doesn't hold person
object(neither does person
).both person
and obj
shares an object.when you create a new object new Object()
,you assign the reference to that object in obj
.so now obj
holds reference to completely different object.thats why you cant mutate person
object anymore.
Upvotes: 0
Reputation: 71058
obj
, even though it is the name of the argument, behaves like a local variable within the setName
function. When the function is called, it refers to whatever was passed in as the argument. When you set it equal to a new, different object, it's behaving as a local reference, now pointing to the (new) object. At that point, you've lost the reference to the original argument. (And when the function ends, the reference to the newer object is itself lost.)
function setName(obj) { // "obj" is the local variable that will refer to the argument
obj.name = "Pork"; // obj points to the object passed in, which is modified
obj = new Object(); // obj is set to point to a new Object
obj.name = "Chicken"; // the new object is modified.
// the new object is dropped here
}
Upvotes: 3
Reputation: 644
Your analysis appears to be correct. Note that in your existing function you were passing a reference to the object created before it was called. You then overwrote the reference with a reference to the new object.
If you had wanted to construct a new value you would either need to make it the return value of the function or set the new object as an attribute of an argument or as a value in an array.
Upvotes: 0
Reputation: 12142
Every time you use this: new Object()
you are creating a new instance of the object. If you want to change current information you would need to stick with the same variable without creating a new Object()
variable.
Upvotes: 0
Reputation: 3876
Objects are passed as reference in JavaScript, but the reference itself is a value. In other words, you can only change the members of the input object, but not its reference. What happens in the line
obj = new Object();
is that the local copy of the reference to "obj" is modified, but this local copy is discarded when the function returns.
Upvotes: 4