Node.js V8 follows the link

I wonder how memory is controlled in V8. Take a look at this example:

function requestHandler(req, res){ functionCall(req, res); secondFunctionCall(req, res); thirdFunctionCall(req, res); fourthFunctionCall(req, res); }; var http = require('http'); var server = http.createServer(requestHandler).listen(3000); 

The req and res variables are passed each time the function is called, my question is:

  1. Does V8 pass this by reference or make a copy in memory?
  2. Is it possible to pass variables by reference, look at this example.

     var args = { hello: 'world' }; function myFunction(args){ args.newHello = 'another world'; } myFunction(args); console.log(args); 

    The last line, console.log(args); will print:

     "{ hello: 'world', newWorld: 'another world' }" 

Thanks for the help and answers :)

+11
source share
1 answer

This is not what is passed by reference. Passing by reference will mean this:

 var args = { hello: 'world' }; function myFunction(args) { args.hello = 'hello'; } myFunction(args); console.log(args); //"hello" 

And the above is impossible.

Variables contain only references to objects; they are not the object itself. Therefore, when you pass in a variable that is a reference to an object, that link will of course be copied. But the specified object is not copied.


 var args = { hello: 'world' }; function myFunction(args){ args.newHello = 'another world'; } myFunction(args); console.log(args); // This would print: // "{ hello: 'world', newHello: 'another world' }" 

Yes, it is possible, and you can see it just by running the code.

+19
source

All Articles