【问题标题】:Node.js V8 pass by referenceNode.js V8 通过引用传递
【发布时间】:2012-08-09 00:57:25
【问题描述】:

我想知道 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);

reqres 变量在每个函数调用中都会传递,我的问题是:

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

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

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

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

感谢您的帮助和回答:)

【问题讨论】:

    标签: javascript node.js pass-by-reference v8


    【解决方案1】:

    这不是通过引用传递的意思。通过引用传递将意味着:

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

    以上是不可能的。

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


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

    是的,这是可能的,您只需运行代码即可看到它。

    【讨论】:

    • 不确定这是否已经改变。我的代码是 updateRatings(req.body) .then((response) => updateAvgRating({guide: response, rating: req.body})) 我正在修改第一个函数 updateRatings 中的 req.body,而这种变化似乎反映在第二个函数 updateAvgRating
    • @runios 这是因为您的示例中的 body 是一个对象。它是原始值,即字符串和数字。例如。 function foo() {i++;} let i =0; foo(i); console.log(i) 抱歉有点缩小 js ;-)
    • @runios 如果您想更改函数中的原语,请将其包装在一个对象中,例如function foo(i) {i.val++;} let i ={}; i.val=0; foo(i); console.log(i.val) 我忘记了 i 作为我之前评论中的参数,应该是 foo(i)
    猜你喜欢
    • 1970-01-01
    • 2015-01-12
    • 2013-09-10
    • 2020-04-01
    • 1970-01-01
    • 2011-06-28
    • 2015-07-22
    • 2015-05-02
    • 2012-03-13
    相关资源
    最近更新 更多