这是 NodeJS 中的变量范围错误还是我只是需要更多睡眠
在从事 NodeJS 项目时,我遇到了这种非常意外的行为,我无法找到解决方法 - 这对我来说似乎是一个错误,但也许我只是误解了 NodeJS 模块的运行方式。
我将其简化为一个测试用例,如下所示:
mod.js 模块
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
应该(据我所知)永远根本不会被修改。
事实上,cachedObj
肯定也不应该被修改,因为它永远不会从 mod.process
方法返回。我哪里错了?
(运行节点0.6.9)
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 file
var testObj = {one: 'one'}; console.log(['Before:', testObj]); var cachedObj = testObj; require('./mod').process(cachedObj); console.log(['After:', testObj]);
Then running $ node test.js
gives me this:
[ 'Before:', { one: 'one' } ] [ 'After:', { one: 'one', two: 'two' } ]
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.
In fact, cachedObj
should surely never be modified either, as it is never returned from the mod.process
method. Where am I going wrong?
(running Node 0.6.9)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是一个错误,这是完全预期的行为。
JavaScript 中的变量是通过引用传递的,因此原始对象会因
process
中的赋值而发生变化。It's not a bug, it's perfectly expected behavior.
Variables in JavaScript are passed by reference, so the original object is mutated by the assignment in
process
.对象通过引用传递。
由于
cachedObj
和testObj
指向同一个对象(cachedObj === testObj
为true
),因此修改属性cachedObj
也会导致修改后的testObj
。Objects are passed by reference.
Since
cachedObj
andtestObj
point to the same object (cachedObj === testObj
istrue
), modifying a property ofcachedObj
will also result in a modifiedtestObj
.cachedObj
和testObj
引用相同的对象文字,因此如果您修改一个变量,它当然会在两者中看到,因为这些变量只是引用同一对象的别名。另外,JavaScript 中的对象是通过引用传递的,因此如果您在 process.js 中修改它,该对象也会被修改。
cachedObj
andtestObj
refers to the same object literal, so if you modify one variable, it is of course seen in both since the variables are just aliases referring to the same object.Also, objects are passed by reference in JavaScript, so if you modify it inside process.js, the object will be modified.