trogne
trogne

Reputation: 3552

object changed after being passed to another function

How an object can be changed after being passed to another function ? For example :

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function (request, response) {
    response.sendFile(__dirname + '/index.html');
});

'http' is already created, using the previously defined 'app'.

Then, a route is set using app.get. But how is that possible ? How the http server will have access to this route defined after assignment ?

Upvotes: 1

Views: 131

Answers (1)

komron
komron

Reputation: 2277

When you pass an object variable as an argument to a function in Javascript , it is passed by reference. So when you make changes to app outside of http the changes are visible in http because you made changes to the same old object reference of which was passed to http.

Consider this example:

function print(obj) { // -- this is Http in your case
    setTimeout (()=> { console.log(obj.a); } , 1000);
}

var my_obj = { a: 100 }; // -- this is app in your case

print(my_obj); // -- this is passing app to http in your case

my_obj.a = 101; // -- this is adding a route to app in your case

There will be 101 logged into console. Because actual object changes before 1000 milliseconds pass. Global context and a function both still reference to the same object. This proves that objects are passed by reference in Javascript.

If you remove the setTimeout, then there will be 100 logged in to console, here is the snippet:

function print(obj) { 
    console.log(obj.a);
}

var my_obj = { a: 100 }; 

print(my_obj);

my_obj.a = 101; 

Upvotes: 1

Related Questions