I wonder how memory is managed 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 in every function call, my question is:
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);
would print:
"{ hello: 'world', newWorld: 'another world' }"
Thanks for help and answers :)
In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference.
child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.
Node 6 uses V8 release 5 as its JavaScript engine. (The first few point releases of Node 8 also use V8 release 5, but they use a newer V8 point release than Node 6 did.)
That's not what pass by reference means. Pass by reference would mean this:
var args = { hello: 'world' };
function myFunction(args) {
args = 'hello';
}
myFunction(args);
console.log(args); //"hello"
And the above is not possible.
Variables only contain references to objects, they are not the object themselves. So when you pass a variable that is a reference to an object, that reference will be of course copied. But the object referenced 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 that's possible and you can see it by simple running the code.
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