Pass by reference vs value concept with functions

As I understand it, objects are passed by reference in JavaScript (and primitives are passed by value?).

var a, b; a = { Foo: "Bar" } b = a; a.Foo = "Other"; console.log(b.Foo); // "Other" 

This worked similarly to arrays, but did not work, as I expect, with functions:

 var a, b; a = function(){ return 20; } b = a; a = function(){ return 40; } console.log(b()); // returns 20 ? 

I got confused because I thought functions were objects. Should the above example return 40?

+6
source share
4 answers

In the first case, a.Foo = ... , you change the value of the property in the object, denoted by both a and b . This is called mutating an object.

But in the second case, you make a reference to a new function object. Now a and b refer to different objects of the function.

That is why you get 20 in the second case.

+11
source

In addition to the @thefoutheye answer , consider the following proof of your approval functions - these are objects:

 var a, b; a = function() { return 20; } a.Foo = "Bar"; b = a; a.Foo = "Other"; console.log(b.Foo); // "Other" 
+2
source

First, about the question in the header (which is actually different from what you are demonstrating with the code examples):

"As I understand it, objects are passed by reference in JavaScript"

No, Javascript does not support passing a parameter by reference at all. All parameters are passed by value, but the value can be a reference.

Example:

 var a = { answer: 42 }; function f(x) { alert(x.answer); // shows 42 x = { answer: 0 }; alert(x.answer); // shows 0 } f(a); alert(a.answer); // shows 42 

When a parameter is passed by value, the variable x is separated from the variable a , so assigning a new object x does not change the value of a .

Return to your code:

When you assign a link to an object from a variable to another, it copies the link, not the object. You get two variables that reference the same object.

Any of the variables can be used to access the elements in the object that your first code example demonstrates.

If you assign a new object to the first variable, you will replace the link in the variable; you will not overwrite the object it points to. The object remains intact, and the second variable still points to it. You get two variables that point to one object each, which demonstrates your second code example.

+2
source

You reassign the variable a to the new function. This is not the same as changing a property value.

Try:

 var a, b; a = {Foo: function() {return 20;}}; b = a; a.Foo = function() {return 40;}; console.log(b()); // returns 40 
+1
source

All Articles