0

I am running a project with webpack and faced a problem. I solved it but I want to understand how the things are working.

I have an array with module names like [module1,module2,module3]. I use foreach to loop this array and import every module with following syntax.

import('./' + moduleName).then(function (promise) {
      var me = promise.default(element);    
})

In every module I create and return object "me" .Every module has specific functionality and parameters which aren't important for the question.

export default function (element, options) {
     var me = this;
     // some other code
     return me;
}

The problem occurs when I have 2 some modules on one page. The assignment me = this, somehow always create same object with same parameters even when I pass different options.

I solved it by changing the assignment to var me = Object.assign({},this); But I don't understand what is wrong with the first one. Can you give me some explanation?

Nimeshka Srimal
  • 8,012
  • 5
  • 42
  • 57
user2466601
  • 207
  • 1
  • 7
  • 19
  • The behavior seems a result of [pass-by-reference](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Adelin Jul 19 '18 at 10:45
  • It's hard to say for sure without knowing what code is being generated by Webpack. It would also help to see how you are importing each of the modules in your array. – Dan Jul 19 '18 at 10:45

1 Answers1

0

Object.assign clones the object property. but = will copy object's reference.

You can check it in below example.

You can see that me object is assigned using Object.assign and when we change me.x it doesn't reflect in object a. But in second case when we change me2.x it updates value b.x also.

var a = { x: 1 };
var me = Object.assign({}, a);
me.x = 2;
console.log(a);
console.log(me);

var b = { x: 1 };
var me2 = b;
me2.x = 2;
console.log(b);
console.log(me2);
Karan
  • 12,059
  • 3
  • 24
  • 40