javascript Node.js V8 通过引用传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11923419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js V8 pass by reference
提问by onlineracoon
I wonder how memory is managed in V8. Take a look at this example:
我想知道 V8 中是如何管理内存的。看看这个例子:
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:
在req
和res
变量在每个函数调用过去了,我的问题是:
- Does V8 pass this by reference or does it make a copy in memory?
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' }"
- V8 是通过引用传递它还是在内存中进行复制?
是否可以通过引用传递变量,看这个例子。
var args = { hello: 'world' }; function myFunction(args){ args.newHello = 'another world'; } myFunction(args); console.log(args);
最后一行,
console.log(args);
将打印:"{ hello: 'world', newWorld: 'another world' }"
Thanks for help and answers :)
感谢您的帮助和解答:)
回答by Esailija
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.
是的,这是可能的,您可以通过简单地运行代码来查看它。