Simple JS Prototype Example

This is some boilerplate code I sent out recently to describe the JS prototype code I’d been writing:

// create a global MyClass object, intialized to the result of this anonymous, self-executing function
var MyClass = (function() { 

   // constructor function, intializes stuff
   function MyClass($el, options) {
      var self = this;
      self.options = options;
      self.$el = $el;
   } 

   // put functions on the prototype for the constructor function
   MyClass.prototype = {
      myPublicFunction: function() {
         this.$el.doSomething();
      }
   } 

   // return the constructor function, so the MyClass outside of this closure becomes a function
   return MyClass;
});

You can then create an instance of MyClass like this:

var myClass = new MyClass($("#element"), myOptions);

With this pattern, not only can you create multiple instances of the class, but they’ll inherit the same prototype, which means all those prototype functions only get created once, not once for each object you create.

It’s also worth pointing out that it’s a JS convention to only capitalize function names when they’re meant to be used with the “new” keyword, to be treated as objects.

Fun times.