JavaScript Patterns: Build Better Applications with Coding and Design Patterns

Author: Stoyan Stefanov
4.5
All Stack Overflow 18
This Year Stack Overflow 1
This Month Stack Overflow 1

Comments

by anonymous   2017-08-20

There are common JavaScript patterns in this code:

  • The namespace pattern.
  • The immediate function pattern.

The Namespace Pattern

In a browser, the window object is the global scope object. In this example of code that you shared, the programmer created a immediately-invoked function expression and passes the global object window as a parameter, which in the context of the IIFE is bound to the local variable global.

The function, as it names suggests, is immediately invoked when this file is parsed by the browser.

From this point on, global is just an alias for the global scope object window, and the programer uses it to define a namespace app in it.

The namespace basically avoids cluttering the global scope with the objects you need to define and allows the programmer to be more in control of exactly what is defined within his custom scope.

The idea is that from this point forward, you should define all application globals within this customised scope and not within the window global scope, by this avoiding name collisions with other third-party libraries that you are using. This will be a pseudo-equivalent of packages or namespaces in other languages like Java or C#.

Stoyan Stefanov in his book JavaScript Patterns explains it as follows:

Namespaces help reduce the number of globals required by our programs and at the same time also help avoid naming collisions or excessive name prefixing.

JavaScript doesn’t have namespaces built into the language syntax, but this is a feature that is quite easy to achieve. Instead of polluting the global scope with a lot of functions, objects, and other variables, you can create one (and ideally only one) global object for your application or library. Then you can add all the functionality to that object.

The Immediate Function Pattern

The immediately-invoked function is another common JavaScript pattern. It is simply a function that is executed right after it is defined.

Stefanov describes its importance as follows:

This pattern is useful because it provides a scope sandbox for your initialization code. Think about the following common scenario: Your code has to perform some setup tasks when the page loads, such as attaching event handlers, creating objects, and so on. All this work needs to be done only once, so there’s no reason to create a reusable named function. But the code also requires some temporary variables, which you won’t need after the initialization phase is complete. It would be a bad idea to create all those variables as globals. That’s why you need an immediate function—to wrap all your code in its local scope and not leak any variables in the global scope:

(function () {
   var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
   today = new Date(),
   msg = 'Today is ' + days[today.getDay()] + ', ' + today.getDate();
   alert(msg);
}()); // "Today is Fri, 13"

If this code weren’t wrapped in an immediate function, then the variables days, today, and msg would all be global variables, leftovers from the initialization code.

by anonymous   2017-08-20

Node.js allows code to be separated into different modules. This modules are just javascript files that can expose functions or objects using the exports object.

  1. There are more details of this convention
  2. Nice documentation of the Node.js modules

There are no Classes in JavaScript but you can use patterns to emulate that behaviour. There is a question about implementing OOP patterns in JavaScript: what pattern to use when creating javascript class?

As a beginner there are very good books for JavaScript:

  1. JavaScript: The Good Parts
  2. JavaScript Patterns

They are short and will give you a very good insight of the JavaScript Language.

by anonymous   2017-08-20

Not sure if this falls under the category "micro-optimization". I would say no.

But it depends on how often you call doStuff. If you call it often, then creating the function over and over again is just unnecessary and will definitely add overhead.

If you don't want to have the "helper function" in global scope but avoid recreating it, you can wrap it like so:

var doStuff = (function() {
    var doMoreStuff = function(val) {
         // do some stuff
    }
    return function() {
        // do something
        for (var i = 0; i < list.length; i++) {
            doMoreStuff(list[i]);
        }
        // do some other stuff 
    }
}());

As the function which is returned is a closure, it has access to doMoreStuff. Note that the outer function is immediately executed ( (function(){...}()) ).

Or you create an object that holds references to the functions:

var stuff = {
    doMoreStuff: function() {...},
    doStuff: function() {...}
};

More information about encapsulation, object creation patterns and other concepts can be found in the book JavaScript Patterns.

by anonymous   2017-08-20

Nowadays, answers given here are not entirely complete/correct.

Starting from ES5, the literal syntax behavior is the same as RegExp() syntax regarding object creation: both of them creates a new RegExp object every time code path hits an expression in which they are taking part.

Therefore, the only difference between them now is how often that regexp is compiled:

  • With literal syntax - one time during initial code parsing and compiling
  • With RegExp() syntax - every time new object gets created

See, for instance, Stoyan Stefanov's JavaScript Patterns book:

Another distinction between the regular expression literal and the constructor is that the literal creates an object only once during parse time. If you create the same regular expression in a loop, the previously created object will be returned with all its properties (such as lastIndex) already set from the first time. Consider the following example as an illustration of how the same object is returned twice.

function getRE() {
    var re = /[a-z]/;
    re.foo = "bar";
    return re;
}

var reg = getRE(),
    re2 = getRE();

console.log(reg === re2); // true
reg.foo = "baz";
console.log(re2.foo); // "baz"

This behavior has changed in ES5 and the literal also creates new objects. The behavior has also been corrected in many browser environments, so it’s not to be relied on.

If you run this sample in all modern browsers or NodeJS, you get the following instead:

false
bar

Meaning that every time you're calling the getRE() function, a new RegExp object is created even with literal syntax approach.

The above not only explains why you shouldn't use the RegExp() for immutable regexps (it's very well known performance issue today), but also explains:

(I am more surprised that inlineRegExp and storedRegExp have different results.)

The storedRegExp is about 5 - 20% percent faster across browsers than inlineRegExp because there is no overhead of creating (and garbage collecting) a new RegExp object every time.

Conclusion:
Always create your immutable regexps with literal syntax and cache it if it's to be re-used. In other words, don't rely on that difference in behavior in envs below ES5, and continue caching appropriately in envs above.

Why literal syntax? It has some advantages comparing to constructor syntax:

  1. It is shorter and doesn’t force you to think in terms of class-like constructors.
  2. When using the RegExp() constructor, you also need to escape quotes and double-escape backslashes. It makes regular expressions that are hard to read and understand by their nature even more harder.

(Free citation from the same Stoyan Stefanov's JavaScript Patterns book).
Hence, it's always a good idea to stick with the literal syntax, unless your regexp isn't known at the compile time.

by anonymous   2017-08-20

A constructor is just a normal function. There is nothing special about it inherently.

All functions have a property called prototype.

If you write

var myInstance = new MyFuction();

JavaScript does something special with your function when it executes it.

It sets the value of this inside the function body to be myInstance. Additionally, it creates a reference to MyFunction.prototype and stores it as an internal property of myInstance.

When your code is executing, the rule that the interpreter follows is such that, if you try to access a property on myInstance that it can't find, it will follow that reference to the function's prototype and look there. This forms a chain, known as the prototype chain that leads all the way up to Object.prototype.

Here's an example:

function Dog(name, breed) {
  this.name = name;
  this.breed = breed;

  //if you don't specify a return value, `this` will be returned
}

Dog.prototype.speak = function() {
  alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
}

var myDog = new Dog('buttercup', 'poodle');
myDog.speak();

The snippet above works, but if you run: console.log(myDog) you'll see that it does not have a speak method. the speak method was found in it's prototype.

This means that all 'instances' of Dog that are created will all share the same speak method.

So, If I create another dog, it will be able to speak aswell:

var tommysDog = new Dog('rosco', 'pitbull');
tommysDog.speak(); //tommy's dog can speak too

  
    function Dog(name, breed) {
      this.name = name;
      this.breed = breed;

      //if you don't specify a return value, `this` will be returned
    }

    Dog.prototype.speak = function() {
      alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
    }

    var myDog = new Dog('buttercup', 'poodle');

    var tommysDog = new Dog('rosco', 'pitbull');
    tommysDog.speak();

It also means that if I change the value of Dog.prototype.speak at run time, all instances will be affected.


Note: technically, functions do have a constructor property but it's not that important and it would just confuse you more if I tried to explain it here.

I suggest you read the mozilla docs

Additionally, I suggest you read this book. You'll learn a lot about proper design.


Also note that this is just one way to achieve code re-use. You don't have to go through prototypes at all. In fact JavaScript has methods that let you supply arbitrary values as the value of this to functions as an argument.

This means that, even though my pet lizard can't normally speak, I can just borrow the method from Dog.prototype by utilizing a method like call() or apply(). (All functions have these methods because they 'inherit' them from Function.prototype.)

function Dog(name, breed) {
  this.name = name;
  this.breed = breed;

  //if you don't specify a return value, `this` will be returned
}
Dog.prototype.speak = function() {
  alert('Ruff, I\'m ' + this.name + ' the talking ' + this.breed);
};



function Lizard(name, species) {
  this.name = name;
  this.species = species;
}

Lizard.prototype.speak = function() {
  var pretend_dog = { name: this.name, breed: this.species };
  Dog.prototype.speak.call(pretend_dog);
};

var myLizard = new Lizard('larry', 'chamelion');
myLizard.speak();

by raju   2017-08-19
Every good resource that I can think of has already been listed by @dutchrapley, with the exception of 1 (so he gets my vote :D) - Once you finish reading 'The Good Parts' and 'JavaScript Ninja' take a look at 'JavaScript Patterns' by Stoyan Stefanov [www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752/]

On a related note, there was some interesting discussion right here on HN with regards to Addy Osmani's JS Patterns eBook - http://news.ycombinator.com/item?id=2762888

by grobertson   2017-08-19
And when you're done those, JavaScript Patterns is something you'll refer to often.

http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp...

by makuro   2017-08-19
http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp...

Boom. Get it while it's hot.