Node.js V8通过引用传递

onl*_*oon 11 javascript v8 pass-by-reference node.js

我想知道如何在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);
Run Code Online (Sandbox Code Playgroud)

reqres变量在每个函数调用过去了,我的问题是:

  1. V8是通过引用传递还是在内存中复制?
  2. 是否可以通过引用传递变量,请看这个例子.

    var args = { hello: 'world' };
    
    function myFunction(args){
      args.newHello = 'another world';
    }
    
    myFunction(args);
    console.log(args);
    
    Run Code Online (Sandbox Code Playgroud)

    最后一行,console.log(args);将打印:

    "{ hello: 'world', newWorld: 'another world' }"
    
    Run Code Online (Sandbox Code Playgroud)

感谢您的帮助和答案:)

Esa*_*ija 19

这不是通过引用传递的方式.通过引用传递意味着:

var args = { hello: 'world' };

function myFunction(args) {
  args.hello = 'hello';
}

myFunction(args);

console.log(args); //"hello"
Run Code Online (Sandbox Code Playgroud)

以上是不可能的.

变量只包含对象的引用,它们本身不是对象.因此,当您传递一个作为对象引用的变量时,该引用当然会被复制.但是不会复制引用的对象.


var args = { hello: 'world' };

function myFunction(args){
  args.newHello = 'another world';
}

myFunction(args);
console.log(args); // This would print:
    // "{ hello: 'world', newHello: 'another world' }"
Run Code Online (Sandbox Code Playgroud)

是的,这是可能的,你可以通过简单的运行代码看到它.