theboywhocriedWoolf | Tal Woolf

Require.js and Inheritance

2

With NodeGarden & ParticleWall

When getting to grips with a new programming language it’s easy to feel lost and confused; like standing at a busy cross road in a foreign county not knowing which way to turn, getting no help from your iPhone and funny looks from the locals. The important thing to remember is that all languages at their core are pretty similar and although the syntax might differ your approach and methodology should remain pretty consistent. This is also true with JavaScript, not that JavaScript cares about these things, but you should.

Coming from more object oriented languages at first it was hard for me to get accustomed to JavaScript’s complete lack of structure. Luckily, its evergrowing popularity has brought alongside it some amazing advancements with frameworks and libraries to help combat this and bring order to the chaos.

Therefore recreating my NodeGarden and ParticleWall using JavaScript and Canvas proved to be a relatively easy task.

Require JS

If you are building a smallish application and don’t need to involve the heavy artillery of frameworks, then Require.js is the one for you. It has everything you need to start making neat little modular applications and because of its structure and use it almost forces you to apply some kind of OOP approach to your code.

Require.js is easy to use;  you simply divide your application into modules, just as you would classes, and then define their dependencies, which as it happens Require.js automatically loads in for you. This allows you to separate all your JS files into nicely contained components or modules only loading in the JS files as and when you need.

For an in depth explanation of its use and capability I suggest you read the Require.js API documentation. Alternatively, Gary Stevens has written an enlightening little article on how to achieve Better JavaScript organisation with Require.js.

Module me this

Require.js is based on modules so I felt it was only right to try and adhere to the Module Pattern when using it within my application. The Module Pattern is a good way to control the interface of your components features, encapsulating your core functionality, whilst hiding its private methods from prying eyes and twitchy fingers.

The pattern provides a nice way to implement both private and public methods by limiting their scope and wrapping them in a closure. It’s a good way of shielding parts of your applications from global scope.

Achieving the above is effortless; simply create a Function, or as I now like to refer to them a ‘Module Class’, which will return an object. Anything that is appended to the returned object is deemed as public, whilst the rest of your functionality is private and hidden from the global scope.


// defines your module and loads any dependencies
define(["js/dependencies.js"], function()
{

     // encapsulated in a Module Class / Function
     // to enable instantiation
     var ModuleClass = function()
     {
          var privateVariable;
          var secondPrivateVariable;

          // only accessible to local scope

          function privateFunction( value )
          {
               // method body

          }
           // return public methods and properties
           return {
                      publicFunction : function( value )
                      {
                           // access to local scope properties
                           privateVariable = value;
                      },
                      publicVariable : "",
                      // can even assign private to public
                      publicMethodTwo : privateFunction
                 }
      }
})

Inheritance – Who’s Yer DADDY?

Inheritance is something we often take for granted when working with more structured languages, giving it little thought as we layer up our code cake, only stopping to take note once it’s nowhere to be seen.

Although JavaScript is a prototypal language and it can’t actually achieve classical inheritance in the same way a more structured OOP language is able to. There are luckily as few ways we can imitate this behaviour by using what’s referred to as “pseudo-classical Inheritance”.

The first approach I used within my application was to create a Parent Base Class using the Module Pattern approach encapsulating all my repeated logic, exposing only an interface of public methods and properties.

I then loaded this module in as a dependency in my sub-class,  enabling me access to all of its public methods and properties.


// load in the Base Class as a dependancy
define(["js/ParentModuleClass.js"], function( BaseModuleClass )
{
      // encapsulated in a Module Class / Function
      // to enable instantiation
     var ModuleClass = function()
     {
          // get an Instance of  BaseModuleClass
          var _appBase = new BaseModuleClass()
          // only accessible to local scope

          function init( )
          {
               // method body
               _appBase.initSomething()

              // set properties on BaseClass
              _appBase.setProp( 10 )

          }

         // return public methods and properties
         return {
                   publicFunction : function( value )
                   {
                        // access to local scope properties
                        privateVariable = value;
                   },
                   publicVariable : _appBase.getValue()
              }
      }
})

To use this method successfully you must make sure you create an Instance of the Parent Class when sub-classing it, otherwise your Module will act as a Singleton across all of its sub-classes. Require.js does provide the ability to use different contexts for each JS file loaded, but if this is not specified in the initial configuration then you will  end up using the same object throughout the entire application.

This approach is fine if sub-classing just one level but soon proves to be a little tricky when adding further layers of inheritance. You end up having to add public getters and setters in your Child Class simply to change properties within the Parent Class, which less face it, removes the point of inheritance.

Because of this I decided to look into John Resig’s Simple JavaScript Inheritance. This is a much nicer way of performing inheritance and reacts in a more familiar way.

Resig has created a nice JavaScript Class, that when sub-classed, provides you with all the functionality you should be accustomed to, such as full access to all your Parent Class’s methods and properties, ability to override methods and even a Constructor.

To use the Class simply load it in to your Parent Base-Class and create your Module Class using “Class.extend({})”.


// load in the Base Class as a dependancy
define(["js/ParentModuleClass.js"], function( BaseModuleClass )
{
      // Extend the Base class taking on all its
      // methods and properties - can keep on sub-classing up the chain
      var ModuleClass = BaseModuleClass.extend(
      {
           init : function()
           {
              // constructor
           {
      }}
})

This,with out a doubt, provides  a neater approach when using Inheritance,. However, it does not provide a way of creating private methods and properties. There are a few ways to overcome this, but none of these  really solve the problem they just kind of tiptoe around it.

The first, in a similar way to the Module Pattern, is to create methods and properties outside of the class object itself. That way they are still accessible to the object, but remain within the scope of the Module. However, within this solution arises another problem, because outside of the objects scope the properties and methods remain static throughout the Class’s instances creating kind of Singleton effect.

The second is a more of a naming convention which developers tend to use, as apposed to an actual solution.  This is to place an underscore in front of all private methods. This doesn’t prevent them from being accessible, but it does (rather simply) illustrate to other developers that they’re intended for internal use only.

The final method is similar to Resig’s approach in that each time an instance is created it copies the Parents Class prototype information and appends it to its own.

You can find out how to implement this approach within Ben Nedals blog post ”Using Require.js for Asynchronous Script Loading and JavaScript Dependency Management”.

Plug Me In

If you end up using a plugin for any of your scripts, for example I used the JQuery easing plugin, you may find that occasionally your JavaScript decides to throw an error your way.

For a while this baffled me, how can my application work one minute and not the next in the absence of any changes? So with JavaScript’s exceptional debugging support on my side, basically a case of going through the code and having to console.log() nearly everything myself,  I finally found the problem.

Require.js tries to load your JavaScript files in the most efficient way it can which can sometimes mean that your plugins end up loading before your component has completed loading which causes you errors. Luckily Require.js also provides a nice way around this called “shim”.

When using shim all you need to do is specify the plugin you are loading and then list its decency / dependencies before your main require function:

requirejs.config
({
      shim:
      {     // specify your plugin and then dependencies
            'jquery-plugin-name.js': ['dependency.js', 'another-dependency-if-needed.js'],
      }
});
// main require function call
require( function() {} );

As with anything, no one solution fits all. And in this instance I wasn’t really looking for solution, for me,  it was more about having an opportunity to play around with inheritance. However, as any good Design Patterns book will advise you, favour composition over inheritance, and I tend to agree.  If you are thinking of taking a more modular approach, Mike West discusses this in his post “Evolve Your Hierarchy”. Or alternatively if you are planning on making a larger application and need more structure and control I suggest you look into Backbone.js.

Feel free to check out the JavaScript version of NodeGarden and ParticleWall or alternatively, Spoon me on GitHub.

Discussion

  1. Mannu

    hi this is a nice article, thanks for sharing. Can you please share the boilerplate code for “Class.extend({})” solution. i don’t know how to create the base module for this approach

    • boycriedwoolf

      Hello, if you take a look at John Resig’s Class example, all you need to do is include his Class.js file and have your base Class extend Class. You will then be able to extend your base Class.

      I hope this makes sense.

Leave a Reply to boycriedwoolf / Cancel Reply

(* Required)