JavaScript Design Patterns: Module

I was instructed to learn about JS design patterns so I took a PluralSight course on it, which sucked and didn’t teach me anything I needed to know. Update: I trashed it in a review on the website, and a whole bunch of other users commented on my review with similar experiences. PluralSight responded by removing the course from the JS path and replacing it with a new one! My manager said ‘not those patterns—these ones.’ And I don’t understand anything I’m reading because I don’t know the basics. So I’m going to try to look at each line of this blog post, paraphrase it, and define terms where they need to be defined so that I can make sense of them.

1 Module Design Pattern

Devan Patel: 4 Javascript Design Patterns You Should Know

JS modules are the most popular for keeping parts of code independent of other components.
What is a component?

1.1 Components

Nick Salloum: JavaScript Objects: JavaScript Objects & Building A JavaScript Component – Part 1

1.1.1 About Objects and JS

An object is a collection of things. Its things are properties. A bike is an object. Some of its properties are its manufacturer and model. It also has components, which have their own properties. I don’t think that the bike components are the same as the components we’re trying to understand, but they might be. We’ll see. A bike component would be the seat, the bell, wheels, etc. So, the bell may have a manufacturer, which would be a property of the bell. And so forth.

Some properties are predefined. Others we can create ourselves. Also, some of them are functions, and then they’re known as methods. A method on a bike, I guess, would be go or get stolen since these are things bikes can do.

1.1.2 Object Creation

Except null and undefined—everything else in JS is an object. That means they all have properties.

So let’s create an object.

var myBike = new Object();

When I do this, not much happens. But apparently, I now have a bicycle. I can add properties to it now.

var myBike = new Object();

myBike.make = "Firmstrong";
myBike.model = "Bruiser";
myBike.color = "Black";

console.log(myBike)

And now my bike and its properties have been output, and I can access them anywhere in the script. So if I wanted to get the model of the bike, I could do this:

console.log(myBike.model)

This is just one way to make an object. There are other ways too. But I still don’t know what a component is.

1.1.3 Creation of an Object: Object Initializers

So, another way to make this same object would be like this:

var myBike = {
  make: 'Firmstrong',
  model: 'Bruiser',
  color: 'Black'
}

console.log(myBike)
console.log(myBike.model)

It wraps everything up a little neater. Okay, so getting back to the functions / methods mentioned above.

var myBike = {
  make: 'Firmstrong',
  model: 'Bruiser',
  color: 'Black',
  go: function(){
    console.log("I'm going places!")
  }
}

myBike.go();

And now when I tell my bike to go, it goes places. If a property’s value is a function, it’s known as a method. So this is my bike’s go method. If this was a video game, and someone said to make the bike go, I’d say myBike.go() and my bike would be going. I still don’t know what a component is.

1.1.4 Creation of an Object: Constructor Function

So, I think the last one is the “object literal” notation. In that case, from what I can tell, my bike is the only bike in the world. If I want another bike, I have to make myBikeToo, and then define its properties there. I didn’t read this anywhere, I’m just guessing. So, there’s this other way, an object constructor where I can make a bike factory, pretty much, and I can tell it to make me bikes that all have the same sorts of properties. Like, every bike has a manufacturer, even if it’s just some dude. And every bike has a color, even if it’s just ‘metal’, and every bike has a model, even if it’s just ‘I don’t know’. But instead of having to write this out for each bike, we can shorthand it.

function Bike( make, model, color ){
  this.make = make;
  this.model = model;
  this.color = color;
  this.go = function(){
    console.log("My " + this.color + " bike is going places!")
  }
}

var myBike = new Bike( 'Firmstrong', 'Bruiser', 'black');

console.log(myBike);
myBike.go();

And the output is:

Object { make: "Firmstrong", model: "Bruiser", color: "black", go: Bike/this.go() }
My black bike is going places!

So how can we remember the difference between these two? Okay, an object literal is an object we create by spelling it out, whereas an object constructor creates objects like a factory—we don’t spell it out, the factory spells it out for us.

1.1.5 Building Blocks For Our Component

Finally, he used the word “component”—I feel like we might learn what a component is soon. Unfortunately, the first thing that happens is we jump into code that I don’t understand.

;(function( window ) {
  'use strict'; 
})( window );

Explanation: “We are passing window into our self-executing function so that we can later add our SimpleAlert component to the global namespace.” A self-executing function that we pass window into so that we can later add it to our global namespace. AWESOME.

Let’s go down that rabbit hole. Google, javascript what is a self-executing function?

1.1.5.1 Self-Executing Anonymous Functions

Here’s some code that works:

var bikeShoes = "rubber";
var workShoes = "leather";

function allMyShoes(){
  return bikeShoes + ' and ' + workShoes;
}

console.log(allMyShoes());

It works because it’s such a tiny script. If it was larger, it would “litter the global namespace.” There’s that term again. “Global namespace”.

1.1.5.1.1 The Global NameSpace

StackOverflow: Understanding the JavaScript Global Namespace and Closures

Everything belongs somewhere. The earth is part of our solar system, which is part of our galaxy, which is part of our universe. Or something like that. So your code exists in something similar.

function milkyWay(){
  var ourSolarSystem;
}

Okay, but—what about the universe? That’s the “global namespace”. But what is it? It’s the window. The browser window. Which probably exists in the browser, which exists in your OS, which exists somewhere else until you get into the physical world, which leads us back to the real-life universe. For what we’re doing though, we’re ultimately stuck inside the window—anything we do is limited to that browser window. Which, I guess is a good way of thinking about what’s inside it too. Things in a function are generally limited to that function, right? So, anything in that top level of the window is accessible to everything else in that top level, or at lower levels.
But there’s only room for so many named things in any one place, sort of like everyone you know has basically the same ten names. And sometimes it gets confusing, so you use either last names or an additional qualifier, like “first-floor John” or “smelly John.” So,

var shoeOfJohn;
can coexist with and contain a different value than:
function smellyJohn() { 
  var shoeOfJohn;
}

The reason being that you could get into trouble if you accidentally mistake one variable for another. And that trouble really begins once you have things just hanging out in the global namespace. For instance, if you load up a script that someone else wrote, and it also has a shoeOfJohn variable in the global namespace.
What’s a namespace, though?

1.1.5.1.1.1 Namespaces

Javascript namespaces immediately jumped us back in the Module pattern, with a note from the author that he’s using it most frequently now, as well as another note that it’s both unintuitive and unreadable.

Angus Croll: Namespacing in Javascript

Halfway through, I suddenly feel like I kind of understand what’s going on. And then he’s like “don’t stop at Modules—there’s something better.” But I AM stopping at Modules, because that’s the goal in this exercise, and beyond that there are other patterns I need to learn!

So, to Wikipedia, who’s able to reduce it to its broadest definition, which makes it all clear. It’s basically a symbol that lets you reuse the same names in different places, with different meanings. So, let’s say you’re a regular American and you hear that a hundred people were shot in Georgia. What do you do? Do you become outraged for one reason or another, or do you say “so what?” Your decision is based on namespacing.

unitedStates.georgia = "I'm outraged because there’s either too many or not enough guns!"

europe.georgia = "Is Europe part of Paris, or the other way around?"

unitedStates and europe are the namespaces in this example.

1.1.5.2 Self-Executing Anonymous Functions, continued…

Mark Dalgleish: Self-Executing Anonymous Functions

So, let’s repeat how we began before and see if it makes more sense now. Here’s some code that works:

var bikeShoes = "rubber";
var workShoes = "leather";

function allMyShoes(){
  return bikeShoes + ' and ' + workShoes;
}

console.log(allMyShoes());

It works because it’s such a tiny script. If it was larger, it would “litter the global namespace.” Right! Because if this was our code, the global namespace would have three things in it: bikeShoes, workShoes, and allMyShoes. Now we have to remember not to use those for other things, for instance, counting the number of bike shoes, or Boolean value to let me know whether or not I own a pair of bike shoes.

So, the self-executing anonymous function. Here’s his example:

(function(){
  console.log('Hello World!');
})(); 

When broken down, it has two parts. The anonymous function part:

(function(){
  console.log('Hello World!');
})

which, when compared to the same function with a name

function helloWorld(){
  console.log('Hello World!');
}

shows that they’re basically the same, except one has a name, and the other just has a (). Also, the anonymous one is all wrapped up in a (). And then there’s the second part…

();

This makes everything that happens before it run. So, usually you’d call a function like: helloWorld() – or, like in jQuery,

$(document).ready(function(){ 
  console.log('hello world') 
}); 

it’s run when something magical tells it to run, which in this case is the document being ready. The blog then rapid-fires the following terms: function level scoping, closure. Yikes! Let’s just stay away from those until we absolute need to explore them further. If we write to reflect what we just looked at:

(function () {
  var bikeShoes = 'rubber';
  var workShoes = 'leather';
  function allMyShoes() {
    return bikeShoes + ' and ' + workShoes;
  }
}) ();
console.log(allMyShoes());

This throws an error. Okay, I don’t even know what throws means—I just hear other people use it. What I mean is, this makes an error pop up: Exception: ReferenceError: allMyShoes is not defined. That’s because it’s all self-contained and, remember, it can reach back out to things in the global namespace, which is the browser window, but the browser window cannot reach into this function. Particularly since we didn’t give it a name, I guess, so we don’t even know what to call it. In this next example, only one thing is different—the window.allMyShoes = allMyShoes bit. So, since the browser window AKA window is the global namespace, we’re saying that in the global namespace, which we have access to, make this variable called allMyShoes, and assign to it all these things from our function allMyShoes.

(function () {
  var bikeShoes = 'rubber';
  var workShoes = 'leather';
  function allMyShoes() {
    return bikeShoes + ' and ' + workShoes;
  }
  window.allMyShoes = allMyShoes;
}) ();

console.log(allMyShoes()); 

So I guess that’s nice—because now we have access to all three of those names, but the global namespace is only cluttered up by one (allMyShoes) instead of three (bikeShoes, workShoes, allMyShoes). What makes everybody all excited about this is that you have control of what’s available outside the function. So, we could make all three of these names available—or none. Apparently, that’s called privacy.

Lastly, we can do this:

(function (window) {
  var bikeShoes = 'rubber';
  var workShoes = 'leather';
  function allMyShoes() {
    return bikeShoes + ' and ' + workShoes;
  }

  window.allMyShoes = allMyShoes;
}) (window);

console.log(allMyShoes());

The only reason he gives is that it’ll allow for easier minification later. But it illustrates that this is how we’d pass an argument into our anonymous function.

1.1.6 Building Blocks For Our Component, continued…

So! Now we know what a self-executing function is. Here’s what got us all confused before:

Nick Salloum: JavaScript Objects: JavaScript Objects & Building A JavaScript Component – Part 1

;(function( window ) {
  'use strict'; 
})( window );

Explanation: “We are passing window into our self-executing function so that we can later add our SimpleAlert component to the global namespace.”

None of this made sense before, but now I can look at it and see the following: it’s a self-executing anonymous function. We’re passing window into it. Do we need to pass window into it? No, because it’s the global namespace, but I guess it’s just the right thing to do. Why does it begin with a semicolon? I seem to recall reading long ago that it’s just a quick way to make sure that this code isn’t interpreted as being part of some other line. LET’S FIND OUT! Like, if I wrote:

var name = "stephen"
var me = name

No problems. JavaScript is smart enough understand when I’m just being lazy. I don’t need semicolons at the ends of the lines. In this case, though:

var name = "stephen"
var me = name

 (function (window) {
  function yoVanilla() {
    return 'word to your mother';
 }  
  window.yoVanilla = yoVanilla;
 }) (window);

console.log(yoVanilla());

I’d end up with a TypeError: name is not a function. And that’s because it reads it as:

var me = name(function(window){
    …etc…

So what we need is a semicolon in there somewhere. So if I put it before the function, then I’m just defending against my own forgetfulness.

As for strict mode—I’ve read about it enough to know that sometimes JavaScript produces errors and you can be like ‘oh, I broke something.’ And other times it produces ‘silent errors’ and you’re like ‘my code’s great!’ when really it’s just that nobody told you that it’s in bad shape. Strict Mode makes it so you see those silent errors. Why is this good or bad? I don’t know except that when I’m running a CSS linter it’s always like OMG your rules aren’t in alphabetical order!!! and then it shuts down because it can’t handle the number of errors. What I’d prefer it to do is just show me things like ‘this is an unexpected token, and that’s why your page is broken.’

So here’s our code:

;(function (window) {
  'use strict';
  function YoVanilla(message) {
    this.message = message;
  }
  window.YoVanilla = YoVanilla;
}) (window);

It doesn’t do anything yet. So, here’s some HTML—and, again, I am pretty much just taking and barely modifying the tutorial code that I’m reading:

<div id="component">
  Show Default Yo
  Show Success Yo
  Show Error Yo
</div>

Now, we add this:

(function(){
  var defaultBtn = document.getElementById("default");
  defaultBtn.addEventListener("click",function(){
    var defaultYo = new YoVanilla("word to your mother.")
    defaultYo();
  })
})();

So, before he continues, he discusses Object.prototype. I very nearly got up and went out to take a walk, but just as I was standing up it began making sense to me. Remember how somewhere way up near the top I mentioned that pretty much everything in JS is an object? And that we can give objects properties, but also they come with some? Well, I didn’t really know what they came with when I said that. It’s like watching a dog do dog things—how do they know how to do that? Well, they come with dog behaviors. And then you take them to class and teach them more behaviors too. Which is why dogs all pretty much sit the same way, but some dogs can ride skateboards and others can’t. So, with objects, they can all sit—that’s built in. But it’s up to you to teach them how to ride skateboards. The place where objects keep all their built-in properties is in prototype.

So, now he’s adding onto the object’s prototype like this…

;(function (window) {
  'use strict';
  function YoVanilla(message) {
    this.message = message;
    this._init();
  }

  YoVanilla.prototype._init = function() {
    console.log(this.message)
  }

  window.YoVanilla = YoVanilla;
}) (window);

(function(){
  var defaultBtn = document.getElementById("default");
  defaultBtn.addEventListener("click",function(){
    var defaultYo = new YoVanilla("word to your mother.")
    defaultYo;
  })
})();

Although, I’m not sure what the benefit of that over the following is:

;(function (window) {
  'use strict';
  function YoVanilla(message) {
    this.message = message;
    this._init = function() {
      console.log(this.message)
    }
    this._init();
  }

  window.YoVanilla = YoVanilla;
}) (window);

(function(){
  var defaultBtn = document.getElementById("default");
  defaultBtn.addEventListener("click",function(){
    var defaultYo = new YoVanilla("word to your mother.")
    defaultYo;
  })
})();

And that’s part of the problem I have with the documentation—it tends to be written for people who have had to write workarounds in the past or are familiar with other languages and find JS lacking expected features. Anyhow…

;(function (window) {
  'use strict';
  function YoVanilla(message) {
    this.message = message;
    this._init();
  }

  YoVanilla.prototype._init = function() {
    this.component = document.getElementById("component");
    this.box = document.createElement("div");
    this.box.className = "yo-vanilla";
    this.box.innerHTML = this.message;
    this.component.appendChild( this.box );
  }

  window.YoVanilla = YoVanilla;
}) (window);

(function(){
  var defaultBtn = document.getElementById("default");
  defaultBtn.addEventListener("click",function(){
    var defaultYo = new YoVanilla("word to your mother.")
    defaultYo;
  })
})();

And now the prototype offers new tricks to the objects that inherit from it. Here’s the rest of the code with the other buttons working, also I’m trying to learn to comment better, so now there’s some nice comments in there too. Again, everything is just copied/modified from that same blog post: Nick Salloum: JavaScript Objects: JavaScript Objects & Building A JavaScript Component – Part 1

;(function (window) {
  'use strict';

  /**
  *
  * Yo Vanilla function
  */

  function YoVanilla(message) {
    this.message = message;
    this._init();
  }

  /**
  * Initialize the message
  */

  YoVanilla.prototype._init = function() {
    this.component = document.getElementById("component");
    this.box = document.createElement("div");
    this.box.className = "yo-vanilla";
    this.box.innerHTML = this.message;
    this.component.appendChild( this.box );
    this.initUIActions; // this is new
  }

  YoVanilla.prototype.initUIActions = function(){
    // nothing in here yet
  }

  /**
  * Add YoVanilla to global namespace
  */

  window.YoVanilla = YoVanilla;
}) (window);

// EVENTS
//
// The code for creating new object instances
// depending on which button pressed
/////////////////////////////////////////////////


(function(){

  /** show default
  *
  */
  var defaultBtn = document.getElementById("default");
  defaultBtn.addEventListener("click",function(){
    var defaultYo = new YoVanilla("word to your mother.")
    defaultYo;
  })

  /** show success
  *
  */
  var successBtn = document.getElementById("success");
  successBtn.addEventListener("click",function(){
    var successYo = new YoVanilla("to the extreme i rock the mike like a vandal");
  })

  var errorBtn = document.getElementById("error");
  errorBtn.addEventListener("click",function(){
    var errorYo = new YoVanilla("stop, collaborate, and listen")
  })

})(); 

And here’s some other great Vanilla Ice quotes worth reading

So I feel like I understand what a component is in this context…it’s a reusable bit of code. If I had something larger I was working on, I guess I could customize any number of buttons for the user to click on that would result in an alert with some custom message. As much as I’d like to continue to Part 2 of the tutorial, the goal was just to get some understanding of component-ness, and I suppose that I’ve reached that. Part 2 is here.

2 Module Design Pattern, continued…

So, returning to the very first sentence we got stuck on, way up top:

Devan Patel: 4 Javascript Design Patterns You Should Know

“JS modules are the most popular for keeping parts of code independent of other components.”

So, a module is used to keep components from bumping into each other, which is important since components are reusable across a site, so they’ll have ample opportunity to interfere with one another if not isolated! Hooray! I know something new!

The next sentence means nothing to me: “This provides loose coupling to support well-structured code.” Off we go! What is loose coupling? What is coupling? What does it mean to support well-structured code?

2.1 Coupling

Alex Castrounis: How to Write Highly Scalable and Maintainable JavaScript: Coupling

Coupling is when one module directly references another module. That sounds okay. In the example they give, the goal is to create an food order/delivery system. In pseudo-code, it’s like this:

DeliveryModule
   function getDeliveryTime(orderData)

OrderModule
    var orderInfo = { the food order details }
    var estimatedDeliveryTime = DeliveryModule.getDeliveryTime(orderInfo)

Okay, so in this case, the Delivery Module gets its details from the Order Module, and the Order Module gets its details from the Delivery Module. They refer to and rely on each other. This would be considered “tightly coupled.” Why is this bad? I understand these goals, but I don’t understand why coupling hinders them:

  • Modules should be able to be swapped out for other modules
    • Why? If it was a car, should I be able to swap out a wheel for an air conditioner? Sometimes, don’t things need to exist simply because they need to exist?
  • We want to maximize code re-use.
    • In which case, perhaps what the point they’re making is that perhaps the restaurant would add a long-distance delivery of salamis, in which case we’d have a Salami section of the website with a separate order form (since the kitchen won’t be prepping salamis in the same way they prep pizzas for dinner delivery), and rather than write a whole new Delivery Module, both the regular food delivery service and the special Salami delivery service could use the same Delivery Module.
    • Okay, that’s fine, but I still don’t see why the Salami delivery service wouldn’t just pass in its own data, and the Delivery Module would determine how to treat the order—is it food? Okay, send to kitchen. Is it salami? Okay, send to salami warehouse.
  • The ability to test modules independently
    • Also makes sense…but doesn’t data have to come from somewhere? Why can’t modules be disconnected, tested, and then reconnected to one another?

I still don’t really understand—and I don’t feel like any of my questions have been satisfactorily answered.

Okay, so if something is tightly coupled, making changes to one thing could break something else. If two modules are loosely coupled, they will communicate through some middleman. An example given in the Reddit link is of planes communicating with each other—they don’t do so directly, but rather through a control tower. So, to extend that imaginatively, if Plane A needs to know Plane B’s position, Plane B will report its position to the control tower, and the control tower will report the position to Plane A. If Plane B stops reporting its position, however, I don’t see that there’s much difference in whether or not it’s Not Reporting to the control tower or Not Reporting to Plane A. So perhaps that example has its limits. The examples others give are for things like renamed variables not requiring a whole bunch of search/replaces—but rather, rename it once in a function whose name doesn’t change. Again, how is that different than the function’s name changing?

I’m going to tuck this aside as somehow axiomatic, regardless of whether I understand the rationale behind it—if it’s true, then eventually I should understand. “Well-structured code” is likely so broad a term that I’m going to assume it falls in line with, in this situation, loosely coupled modules. If something is tightly coupled, it would not be well-structured, so we want to ensure that as part of well-structured code, we don’t have tightly coupled modules. The end.

3 Module Design Pattern, continueD…

Devan Patel: 4 Javascript Design Patterns You Should Know

“For those that are familiar with object-oriented languages, modules are JavaScript ‘classes’. One of the many advantages of classes is encapsulation – protecting states and behaviors from being accessed from other classes. The module pattern allows for public and private (plus the lesser-known protected and privileged) access levels.”

Whoa. JavaScript classes. Encapsulation. Public. Private.

Okay, the parts I think I may know: if a variable in a function is public, then it can be accessed from outside the function. If private, it can only be accessed within the function itself by the code in the function. Encapsulation is the separation of things.

3.1 Public and Private

“Douglas Crockford: Private Members in JavaScript”
http://stackoverflow.com/questions/55611/javascript-private-methods

How do we make something public or private? Within a function, if a variable begins with this. then it can be accessed from outside the function. If it doesn’t, then it can’t—it’s private.

function Home(){

    var bed = function(){
        console.log("you can't get to me unless you're inside the home");
    }

    this.frontDoor = function(){
        console.log("you can get to me from outside the home");
    }
} 

treehouse = new Home();
treehouse.frontDoor(); // you can't get me from outside the home
treehouse.bed(); // Exception: TypeError: treehouse.bed is not a function

3.2 Encapsulation

StackOverflow: Encapsulation in JavaScript

The first part of the question says it all: “A long time ago, I saw someone encapsulate their entire JavaScript block with code something like the code below…” after which follows an example of a self-executing anonymous function. So,

(function(){
    // I’m encapsulated
})();

But further, encapsulation would also be:

Function(){
    // I’m encapsulated too
}

It would appear to be merely isolating something both from the global namespace as well as from other functions. A further benefit, as described in that StackOverflow post, is that the self-executing anonymous function creates its own little space in the world every time it’s executed. So if you invoke it twice, the two instances of it won’t collide. I don’t know if I’m using the terms “invoke” or “instance” correctly, so I mean them in the most English of senses—if you make the function “go” twice, they’ll be completely different “things” even though they look the same, particularly because they’re unnamed.

Here’s another definition I found when I was looking up the next heading:

“Encapsulation refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application. This allows us to abstract or localize specific set of functionalities on objects.” OOP In JavaScript: What You NEED to Know

3.3 Javascript Classes

OOP In JavaScript: What You NEED to Know

It isn’t said outright here, except like this:

“Inheritance refers to an object being able to inherit methods and properties from a parent object (a Class in other OOP languages, or a Function in JavaScript).”

And then a bunch of stuff about parent/child relationships.

So a class is a set of things used to define objects. In HTML, if we had a bunch of elements and gave them all the class name jumping-beans then we’d know that somehow these elements can all be classified similarly, and that there should be some default properties that should be seen throughout them all (unless overridden). It could be that they’re all colored brown and made to bounce. So they would be, from what I understand, seen as children of the parent class Jumping Beans, even though they could also have individual IDs so they could be assigned additional properties. But prior to ES6, which I don’t know anything about, there are no “classes” in JavaScript. Rather, there’s functions that act like classes. And then things inherit from the function. So,

function JumpingBean(){
    this.color = "brown";

    JumpingBean.prototype.jump = function(){
        console.log("I'm jumping!")
    }

    this.dies = function(){
        console.log("I wasn't even a bean to begin with.")
    }
}

var benny = new JumpingBean();
console.log(benny.color);
benny.jump();
benny.dies();
benny.color = "white";
console.log(benny.color); 

So, Benny inherited some stuff from his class, but after he died, he turned white—which wasn’t something he inherited from the class, but rather a whole new property. Also, there’s some functionality that’s encapsulated in the JumpingBean function—like dies. We could make other things that die also, but they’d die differently. From here I began getting into a mess trying to figure out more inheritance, but again, I think that’s to the detriment of the main point I’m trying to discover.

4 Module Design Pattern, Continued…

Devan Patel: 4 Javascript Design Patterns You Should Know

Time to translate that paragraph:

“For those that are familiar with object-oriented languages, modules are JavaScript classes. One of the many advantages of classes is encapsulation – protecting states and behaviors from being accessed from other classes. The module pattern allows for public and private (plus the lesser-known protected and privileged) access levels.”

JavaScript doesn’t have classes. It has other things. Here it’s calling them modules. Above it’s calling them Functions. [Here](http://www.2ality.com/2012/01/js-inheritance-by-example.html “Axel Rauschmayer: JavaScript Inheritance by Example) it’s calling them Constructors (the object-creation method described up above). Apparently it’s all these things and probably more, and perhaps people disagree—it sounds to me like anything that looks like this function(){ like-this } is one of these things. Anyway, we like them because the stuff inside is encapsulated / isolated from the rest of the script, and it’s easy to set it up for various access levels.

“Modules should be Immediately-Invoked-Function-Expressions (IIFE) to allow for private scopes – that is, a closure that protect variables and methods (however, it will return an object instead of a function).”

4.1 IIFE

Ben Alman: Immediately-Invoked Function Expression (IIFE)

This is how you work with functions. First you declare it:

var a = function(){console.log("hello")}

and then you invoke it.

a()

This works because the first time the browser sees the function name, it assumes it’s being declared. And afterward, that it’s being invoked. If you did

function() { console.log("hello") } 

it wouldn’t work because it needs a name. (SyntaxError: function statement requires a name). So the goal is to have a function that executes itself immediately. So if invoking a function involves nothing more than tossing parents – these things() – after it, then we should be able to do something like

function() { console.log("hello") }()

So now the () should execute the preceding function. But it doesn’t. According to the blog post I’m using for reference, it should be for ‘unexpected token’ reasons—but in Firefox I’m still getting ‘function needs a name’ errors. So, anyway, here’s the trick.

Parens like these () are used in math to determine what order to calculate something, right? So, like 1 + 2 * 3 = 7. But (1 + 2) * 3 = 9. I hope. I was never much good at math.

This wouldn’t make sense:
(1 + 2 = 3) + 4
But this would:
(go count how many apples are in your fridge) + 10

So in code:

function goCountHowManyApplesAreInYourFridge(){
  apples = 3
  return apples
}

allTheApples = goCountHowManyApplesAreInYourFridge() + 10
console.log(allTheApples)

The point of that being that it both makes sense to us on some intuitive, applicable-to-real-life level, and also leads to a reasonable way of thinking about it JavaScript. WHAT?

Okay, so parens are used to group things, but they cannot contain a full statement (like, with an equals sign.) So, that being the case, in JavaScript, if the browser sees something in parens, it assumes it’s not a statement, and so it doesn’t read it like a statement. Because you can’t have a statement in parens—it reads it like it’s not a statement. I think I’ve said it a few different ways now.

So, if you wrap up a function into a little bundle with parens:

(function() { console.log("hello") })

Now the browser thinks it’s basically a grouping of this or that, like (1+2), and if you toss () at the end of it, it should call it like a function. There’s two ways of doing this…which means there’s a high likelihood that my explanation for it all is totally wrong. Because this looks like it makes sense:

(function() { console.log("hello") })();

And this one throws all my ideas out the window:

(function() { console.log("hello") }());

Anyway. Check this out:

var apples = (function(){
  return {
    number: 3
  }
})();

apples.number // 3

There you go. Is that the module pattern? The portion that’s within the return is the public part. The whole thing executes itself immediately, and then we can access whatever was public inside. That was the goal, right?

4.2 Closures

I’ve been dreading this moment because I’ve read countless SO’s and articles on closures and cannot understand what they are—I can’t even figure out what part of speech they are. Until this article: JavaScriptIsSexy.com: Understand JavaScript Closures With Ease.

A closure is a function inside another function.

Sure, there’s more to it than that, but that’s the cut and dry answer. There’s an outer function, and the inner function is the closure. It has access to the outer function’s variables and parameters (but not its argument object). It stores references, not copies, of the outer function’s variables—so if the variable changes, it changes for them all.

5 Module Design Pattern, Continued…

Devan Patel: 4 Javascript Design Patterns You Should Know

“Modules should be Immediately-Invoked-Function-Expressions (IIFE) to allow for private scopes – that is, a closure that protect variables and methods (however, it will return an object instead of a function).”

Okay, so…here we go:

var apples = (function(){
  var applesInFridge = 3;

  var addMoreApples = function(more){
    all = applesInFridge + more;
    return all;
  }

  return {
    number: function(someApples){
      console.log(addMoreApples(someApples));
    },
    numberConsole: addMoreApples(60)
  }
})();

apples.number(6) // prints 9
console.log(apples.numberConsole) // prints 63
apples.applesInFridge // undefined

Now we have an IIFE (immediately-invoked function expression, which is our new, more-correct term for self-executing anonymous function). The three tests at the bottom show that we can still send an argument over the wall, access both functions and variables that are public, and not access anything that’s private.

Well, I guess that’s it. The next step is, as a beginner, to refactor my code and use patterns indiscriminately just because I can.

6 The Module Pattern In Action

6.1 Beginning Code

This example is for a make-believe doctor’s office, where we need to create a medical history for a dummy patient. This code makes up a bunch of dates for some problem (indication), and subsequent follow-up visits, where with each visit the pain level decreases by 1 until the pain is gone and the visits stop until the next medical problem arises.

function Visit(id) {
  this.id = id;
  this.date;
  this.indication;
  this.pain;
}
function RandomDate() {
  this.year = dummyMachine.number(6, 2010)
  this.month = dummyMachine.number(12, 1)
  this.day = dummyMachine.number(29, 1)
}
var dummyMachine = {
  date: function () {
    var source = new RandomDate()
    var date = new Date(source.year, source.month, source.day)
    return date
  },
  indications: [
    'ankle',
    'back, lower',
    'back, upper',
    'elbow',
    'hip',
    'neck',
    'shoulder',
    'wrist'
  ],
  indication: function () {
    // select a random indication from the array
    var indication = this.indications[dummyMachine.number(this.indications.length)]
    return indication
  },
  number: function (upperLimit = 1, offset = 0) {
    return Math.floor((Math.random() * upperLimit) + offset);
  }
}
function createDummyVisits() {
  visits = [
  ]  // create unsorted list of visits
  for (var i = 0; i  0) {
      var currentPain = visit.pain
      for (var indexPain = 1; indexPain  b.date) {
      return 1;
    }
    if (a.date < b.date) {
      return - 1;
    }    // a must be equal to b

    return 0;
  });
  return visits;
}
visits = createDummyVisits()
console.log(visits)

All of this is in the global namespace. Does that mean it’s cluttering it up? I guess so. So, maybe the first thing to change is to put everything in one function.

6.2 First Changes

Now everything is in the dummyContainer, which is an IIFE (immediately-invoked function expression, he wrote in an effort to memorize the phrase). So it doesn’t need to be called anymore, because it executes itself immediately. And if you call it anyway, it does nothing but print and return the list of visits. Everything else is private.

var dummyContainer = (function () {
  function Visit(id) {
    this.id = id;
    this.date;
    this.indication;
    this.pain;
  }
  function RandomDate() {
    this.year = dummyMachine().number(6, 2010)
    this.month = dummyMachine().number(12, 1)
    this.day = dummyMachine().number(29, 1)
  }
  function dummyMachine() {
    return {
      date: function () {
        var source = new RandomDate()
        var date = new Date(source.year, source.month, source.day)
        return date
      },
      indications: [
        'ankle',
        'back, lower',
        'back, upper',
        'elbow',
        'hip',
        'neck',
        'shoulder',
        'wrist'
      ],
      indication: function () {
        // select a random indication from the array
        var indication = this.indications[dummyMachine().number(this.indications.length)]
        return indication
      },
      number: function (upperLimit = 1, offset = 0) {
        return Math.floor((Math.random() * upperLimit) + offset);
      }
    }
  }
  var createDummyVisits = function () {
    var visits = [
    ] // create unsorted list of visits
    for (var i = 0; i  0) {
        var currentPain = visit.pain
        for (var indexPain = 1; indexPain  b.date) {
        return 1;
      }
      if (a.date < b.date) {
        return - 1;
      } // a must be equal to b

      return 0;
    });
    console.log(visits)
    return visits;
  }
  return {
    dummyVisits: createDummyVisits()
  }
}) ();

So I guess that’s fine and interesting. There’s some naming things I’d change now because I think all this dummy stuff looks like I might forget what it is by next week. Also, a line or two that I could make more efficient.

var buildDummyVisits = (function () {
  function Visit(id) {
    this.id = id;
    this.date;
    this.indication;
    this.pain;
  }
  function RandomDate() {
    this.year = createNumber(6, 2010)
    this.month = createNumber(12, 1)
    this.day = createNumber(29, 1)
  }
  function createInitialVisitDate() {
    var source = new RandomDate()
    var date = new Date(source.year, source.month, source.day)
    return date
  };
  function createIndication() {
    var possibleIndications = [
      'ankle',
      'back, lower',
      'back, upper',
      'elbow',
      'hip',
      'neck',
      'shoulder',
      'wrist'
    ];
    var indication = possibleIndications[createNumber(possibleIndications.length)];
    return indication;
  }
  function createNumber(upperLimit = 1, offset = 0) {
    return Math.floor((Math.random() * upperLimit) + offset);
  }
  var build = function () {
    var visits = [
    ] // create unsorted list of visits
    for (var i = 0; i  0) {
        var currentPain = visit.pain
        for (var indexPain = 1; indexPain  b.date) {
        return 1;
      }
      if (a.date < b.date) {
        return - 1;
      } // a must be equal to b

      return 0;
    });
    console.log(visits)
    return visits;
  }
  return {
    dummyVisits: build()
  }
}) ();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s