Why is there so many indirect steps in javascript? for example this module:

Why is there so many indirect steps in javascript? for example this module:
0

#1

Tell us what’s happening:

Why is there so many indirect steps in javascript? for example this module:

let motionModule = (function () {
  return {
    glideMixin: function (obj) {
      obj.glide = function() {
        console.log("Gliding on the water");
      };
    },
    flyMixin: function(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      };
    }
  }
}) (); // The two parentheses cause the function to be immediately invoked

Isn’t it better to remove the function which returns the object and directly assign the object? like this

let motionModule =  {
    glideMixin: function (obj) {
      obj.glide = function() {
        console.log("Gliding on the water");
      };
    },
    flyMixin: function(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      };
    }
  }

What is the difference between these two? Is it just a convention or there is some actual difference? I am new to javascript and I have noted this pattern a lot.


#2

JavaScript did not used to have support for modules. The first piece of code is a way to emulate modules, which are way of structuring codebases, providing encapsulation and organisation. The second one is just an object, it provides no encapsulation.

JavaScript now has native modules so point would be moot, except that support is still patchy at the minute(though rapidly improving). So you’ll see code like the first example for a long time yet

The wiki articles on the subject are quite good


#3

Also, I highly recommend Pro Javascript Design Patterns by Ross Harmes and Dustin Diaz, great intro to both design patterns and how they apply in javascript. A little dated now, perhaps, but most of the patterns are still very significant.

And yes, it introduces the mixin and module concept nicely.