问题描述
在NodeJS项目上工作,我遇到了这个非常意想不到的行为,我无法解决这个问题 - 这对我来说似乎是个错误,但也许我只是误解了NodeJS模块的运作方式。
Working on a NodeJS project, I came a across this very unexpected behaviour that I can't figure a way around - it seems like a bug to me, but perhaps I'm simply misunderstanding how NodeJS modules operate.
我已将其缩减为测试用例,如下所示:
I've reduced it into a testcase as follows:
mod.js module
exports.process = function(obj) { obj.two = 'two'; };
test.js文件
var testObj = {one: 'one'};
console.log(['Before:', testObj]);
var cachedObj = testObj;
require('./mod').process(cachedObj);
console.log(['After:', testObj]);
然后运行 $ node test.js
给我这个:
[ 'Before:', { one: 'one' } ]
[ 'After:', { one: 'one', two: 'two' } ]
我将 testObj
的值分配给 cachedObj
和 testObj
永远不会传递给模块方法。 testObj
应该(据我所知)永远不会修改。
I'm assigning the value of testObj
to cachedObj
, and testObj
is never being passed to the module method. testObj
should (as far as I can see) never be modified at all.
实际上, cachedObj
也一定不会被修改,因为它永远不会从 mod.process
方法返回。我哪里错了?
In fact, cachedObj
should surely never be modified either, as it is never returned from the mod.process
method. Where am I going wrong?
(运行节点0.6.9)
(running Node 0.6.9)
推荐答案
这不是一个错误,它是完全预期的行为。
It's not a bug, it's perfectly expected behavior.
JavaScript中的变量通过引用传递,因此原始对象在<$ c $中的赋值变异c>处理。
Variables in JavaScript are passed by reference, so the original object is mutated by the assignment in process
.
这篇关于这是NodeJS中的变量范围错误还是我需要更多的睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!