Structuring clean Javascript

Status
Not open for further replies.
Hey all. I'm doing some Javascript work (it's an educational game). I've been doing most of my stuff using the Module pattern, which looks something like the following:

Code:
var MyModule = (function() {
  var exports;
  exports.dance = function(type) {
    return type;
  }
  return exports;
})();

But I occasionally see in this codebase I'm working on some other pattern that I don't know the name of:

Code:
var MyOtherModule = {
  process: function(text) {
    return "";
  },
  startup: function() {
    return "Start up";
  },
  shutdown: function() {
    return "Shut down";
  }
}

One thing I figured out was that the second method doesn't allow you to use methods in the other methods (ex: I can't call shutdown within process) without some weird magic that I haven't figured out yet. What's the purpose of the second type of structuring? I haven't quite figured it out yet. Is it for C-style "static" methods in namespaces?

I've been occasionally browsing the numerous blog posts on the Internet about Javascript but I still haven't really wrapped my head around the principles of the language and how to "architect" good Javascript yet. Wondering if anyone here can help provide some specific guidance - and possibly even an example of a small, but good open source project that I can look at and be like, "Wow that's some nice Javascript source code".

Thanks for your assistance.
 

dlp

Ars Tribunus Militum
2,220
[url=http:/civis/viewtopic.php?p=25446297#p25446297:biq9geq0 said:
EmeraldArcana[/url]":biq9geq0]Hey all. I'm doing some Javascript work (it's an educational game). I've been doing most of my stuff using the Module pattern, which looks something like the following:

Code:
var MyModule = (function() {
  var exports;
  exports.dance = function(type) {
    return type;
  }
  return exports;
})();

But I occasionally see in this codebase I'm working on some other pattern that I don't know the name of:

Code:
var MyOtherModule = {
  process: function(text) {
    return "
  },
  startup: function() {
    return "Start up";
  },
  shutdown: function() {
    return "Shut down";
  }
}

One thing I figured out was that the second method doesn't allow you to use methods in the other methods (ex: I can't call shutdown within process) without some weird magic that I haven't figured out yet.
Code:
process: function(text) { this.shutdown(); return "Processing"; }
Me thinks.
 

Mile Zero

Ars Praetorian
578
Subscriptor++
I use the second version in Node and AMD modules to clean up a set of "private" functions into a smaller facade that I present to the API consumer. If the functions are sharing variables via the module closure, or if everything is considered public (i.e., there's no shared state that can't be accessed via this), it's not unreasonable.

If you're not using Require for your client-side code, you really should.
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
I'm a fan of Revealing Module Pattern:

Code:
var MyModule = (function() {

  // "private" variable -- inaccessible outside of the closure
  var skipText = "skipping";

  // "private" method -- not exported in the return statement below
  function privateSkip() {
    return skipText;
  }

  function dance() {
    return "dancing";
  }

  function skip() {
    // Call a "private" method in the closure
    return privateSkip();
  }

  return {
    dance: dance,
    skip: skip
  };
})();

I find that this is easy (for me) to read, explicitly defines the "public" vs "private" methods, doesn't have any impact to calling methods and usually lets you skip dropping 'this's all over the place.
 
[url=http:/civis/viewtopic.php?p=25452183#p25452183:4qrj3acb said:
jxl[/url]":4qrj3acb]The biggest problem that I have with the revealing module pattern is that it makes unit testing kind of... impossible.

I find untested code more distasteful than a larger, possibly more dangerously exposed, set of methods.

Your unit tests are too granular or your modules are too coarse, then. I imagine it's a common problem experienced by people replacing program design with test-first development.
 

Mile Zero

Ars Praetorian
578
Subscriptor++
[url=http:/civis/viewtopic.php?p=25452673#p25452673:ume4lwxe said:
EmeraldArcana[/url]":ume4lwxe]My program co-authors and I haven't been using Require.js. Before I dig into it and potentially use up many hours refactoring, can someone summarize why it's awesome over other non-Require methods?

1. Async script loading: Your page is lighter and shows up faster because it's not blocked by script loading. Instead, Require will go and get the scripts you want after documentready.

2. Dependency management: I'm working on a complicated Chrome app right now. I have a bunch of modules that I need to load, but many of them use other modules. Instead of having to manually order them so that they are all loaded when they're needed, I just declare dependencies and Require works out the order.

3. Script packaging: If you get your application all set up and you go to production, you can run r.js and build a single file with all your scripts ordered and minified, so that it's a single request. This is good for pagespeed, especially on mobile.

4. Loader plugins: AMD modules can be used to load in text or other assets, which is handy when doing templating. At work, we use the YUI loader, which is pretty similar to Require, and we load shared templates directly from the server in the same request as our scripts, which means we're not having to dump them on the page, or hack them in. You can also use this for conditional loading (different modules for different environments).

5. Discipline: I generally find that if everyone has to write Require modules, it's less likely that someone on your team is going to decide to keep writing their personal brand of JavaScript nuttiness. Since AMD modules enforce wrapping everything in a function scope and loads all files asynchronously, it's a good kick in the butt for people who insist on writing JavaScript like it's PHP. It makes you think about your architecture a little bit, without losing people in huge amounts of infrastructure.
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
[url=http:/civis/viewtopic.php?p=25455253#p25455253:3dk5wmhf said:
KallDrexx[/url]":3dk5wmhf]2nd to last time I tried to write modular javascript I got burned by scoping.

Last time I tried to remedy that by having the "public" function call a nested function using javascript's .call(module) to make sure things were scoped correctly. Not sure that's a good practice though but at least it made my life just a tiny bit less frustrating.

I'm not too sure where you would require the use of .call() with a well constructed set of javascript modules? Was this dealing with event callbacks (onClick handlers?) or in some other context? Have an example?
 

Mile Zero

Ars Praetorian
578
Subscriptor++
I have seen people do horrible things with call and function closures for inheritance. The JavaScript mode in Ace does something like this:

Code:
var Mode = function() { /* constructor */ };
(function() {
  this.prototypeProperty = "something";
}).call(Mode.prototype);

They do this because they've already called an inheritance function on the Mode, so they can't just blow away the prototype, and for some ungodly reason they won't just do:
Code:
Mode.prototype.x = y
.

I like Ace, but like any large codebase it has its fair share of WTF moments.
 

KallDrexx

Ars Tribunus Militum
2,040
[url=http:/civis/viewtopic.php?p=25456553#p25456553:34j7hwpc said:
tinyMan[/url]":34j7hwpc]
[url=http:/civis/viewtopic.php?p=25455253#p25455253:34j7hwpc said:
KallDrexx[/url]":34j7hwpc]2nd to last time I tried to write modular javascript I got burned by scoping.

Last time I tried to remedy that by having the "public" function call a nested function using javascript's .call(module) to make sure things were scoped correctly. Not sure that's a good practice though but at least it made my life just a tiny bit less frustrating.

I'm not too sure where you would require the use of .call() with a well constructed set of javascript modules? Was this dealing with event callbacks (onClick handlers?) or in some other context? Have an example?

Yes. I got burned because event handlers were calling module "public" functions and thus scope was becoming unpredictable.
 

Alexandre

Ars Tribunus Militum
1,781
Subscriptor
[url=http:/civis/viewtopic.php?p=25456897#p25456897:1hpw7roe said:
Mile Zero[/url]":1hpw7roe]I have seen people do horrible things with call and function closures for inheritance. The JavaScript mode in Ace does something like this:

Code:
var Mode = function() { /* constructor */ };
(function() {
  this.prototypeProperty = "something";
}).call(Mode.prototype);

They do this because they've already called an inheritance function on the Mode, so they can't just blow away the prototype, and for some ungodly reason they won't just do:
Code:
Mode.prototype.x = y
.

I like Ace, but like any large codebase it has its fair share of WTF moments.
I strongly suggest to not try doing classical inheritance with Javascript. Mixins are a more suitable method for code reutilization with a prototype based language. See http://javascriptweblog.wordpress.com/2 ... pt-mixins/
 
Status
Not open for further replies.