Is this a variable undefined error in NodeJS or do I just need more sleep

While working on a NodeJS project, I came across this very unexpected behavior that I can’t understand the way - it seems to me that this is a mistake, but maybe I just don’t understand how NodeJS modules work.

I brought it to the test file as follows:

mod.js module

  exports.process = function (obj) {obj.two = 'two';  }; 

file test.js

  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 the following:

  ['Before:', {one: 'one'}]
 ['After:', {one: 'one', two: 'two'}] 

I assign the value testObj cachedObj and testObj never passed to the modular method. testObj should (as far as I see) never change at all.

In fact, cachedObj will certainly never be changed since it never returns from the mod.process method. Where am I mistaken?

(running Node 0.6.9)

+4
source share
3 answers

This is not a mistake, this is the expected behavior.

Variables in JavaScript are passed by reference, so the original object is mutated by an assignment in process .

+6
source

Objects are passed by reference.

 var testObj = {one: 'one'}; // <--- Object var cachedObj = testObj; // cachedObj and testObj point to the same object, 

Since cachedObj and testObj point to the same object ( cachedObj === testObj is true ), changing the cachedObj property cachedObj also modify testObj .

+3
source

cachedObj and testObj refer to the same object literal, therefore, if you change one variable, this, of course, can be seen in both cases, since the variables are just aliases related to the same object.

In addition, objects are passed by reference in JavaScript, so if you change it inside process.js, the object will be changed.

+1
source

Source: https://habr.com/ru/post/1398200/


All Articles