0

I'm trying to understand some code :

(function (exports) {

 exports.myProperty = "azerty";

 console.log(exports)

}((this.myModule = this.myModule || {})));

What I understood from this code :

1) I'm executing an IIFE and "this" represents Window (the global object).

2) Since Window doesn't have a myModule property, this.myModule = this.myModule adds a new property to Window object and this property is undefined.

3) (this.myModule=this.myModule) || {} returns {} so exports equals {} (empty object)

4) I'm adding a property "myProperty" to export object so export = {myProerty: "azerty"}

What I don't understand : after executing this code, when I console.log(window), I can see that :

enter image description here

Window object has a property myModule equals to the exports object. How the relation between myModule and {myProperty: "azerty"} has been resolved ? I can't understand this part.

AntonBoarf
  • 1,239
  • 15
  • 31
  • 4
    `this.myModule = this.myModule || {}` is `this.myModule = (this.myModule || {})`, not `(this.myModule = this.myModule) || {}`. – Ry- Jun 12 '18 at 20:58
  • 1
    Objects are reference-type values and are mutable. The object that is passed as `exports` is also assigned to `this.myModule` in `this.myModule = this.myModule || {}`. – Felix Kling Jun 12 '18 at 20:58
  • @Ry : thank you. I just realized that ;) – AntonBoarf Jun 12 '18 at 20:59

1 Answers1

1

Your #3 is wrong. The parenthesis in the original code are like this:

(this.myModule=this.myModule || {})

and it's evaluated like this:

this.myModule = (this.myModule || {})

If a new empty object is created, it is assigned to this.module right away, before being assigned to exports via the function argument. Thus window.myModule and exports are both references to the same object.

Paul
  • 139,544
  • 27
  • 275
  • 264