i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Klass

The concept of formal classes in JavaScript has led the internet develosphere amuck since the dawn of time day JavaScript was invented. From Crock's explanation on prototypal inheritance to Dean's Base one and two, from Prototype's Class to Mootool's Class, and from debunking objects to getting back to basics, the JavaScript community thrives on systems that help make working with JavaScript classes easier — despite it still being a "classless" language.

Well, I'm here to introduce one more that will keep things simple. If you trust every word I say and have no desire to read, then get on with your life and download Klass now on Github.

Klass has no awkward interface to learn and looks more like regular JavaScript aside from some simple helpers to help organize your code. It also supports the CommonJS Module API allowing it to fit nicely into Node.js environments and falls back to exposing the regular interface when a module loader is not found.

So, let's have at the interface...

klass

var Person = klass(function (name) {
  this.name = name;
})
  .statics({
    head: ':)',
    feet: '_|_'
  })
  .methods({
    walk: function () {}
  });

extend

var SuperHuman = Person.extend(function (name) {
  // super class is automagically called
})
  .methods({
    walk: function() {
      this.supr();
      this.fly();
    },


    fly: function() {}


  });


new SuperHuman('Zelda').walk()

implement

because sometimes you want to overwrite OR mixin an instance method...
var Alien = SuperHuman.extend({
  beem: function() {
    this.supr();
    // beem into space
  }
});


if (beamIsDown) {
  Alien.implement({
    beam: function() {
      this.supr();
      // fallback to jets
      this.jets();
    },
    jets: function () {}
  });
}

Environments

Klass comes in two flavors. in your browser:
<script src='path/to/klass.js'></script>
<script type='text/javascript'>
  // exposes 'klass' into current context
  var Foo = klass(fn1);
  var Bar = Foo.extend(fn2)
  Bar.implement({ ... });
</script>
as a module
var klass = require('path/to/klass'),
And that's it! Have a play on the project page and also note... there's tests!

npm users

Already using Node's Package Manager? Easy Peasy.
% npm install klass

Contributing help

Huge thanks to @fat for helping contribute to some core bits in the mess of it.

Cheers.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.