Skip to content

A small, simple implementation of traditional classes and inheritance for JavaScript

Notifications You must be signed in to change notification settings

shinypb/MojoClass

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 

Repository files navigation

mojo.js

A small implementation of classes and inheritance for JavaScript.

Why?

I was working on a project and realized that the whole thing would be infinitely easier with classes and inheritance at my disposal. It seemed like a good time to learn some of the intricacies of implementing such things.

Who?

My name is Mark, and I think you're neat. I'm @shinypb on Twitter.

Example

  // Class declarations
  var Person = mojoClass(function(name) {
    // This is a constructor
    this.name = name;
  }, {
    greet: function(someoneElse) {
      if(someoneElse) {
        return 'Hello, ' + someoneElse + '. My name is ' + this.name + '!';
      } else {
        return 'Hello. My name is ' + this.name + '!';
      }
    }
  });

  var AngryPerson = mojoClass(Person, {
    greet: function(someoneElse) {
      return this._super.greet(someoneElse).toUpperCase();
    }
  });

  // Class usage
  var mark = new Person('Mark');
  console.log('Person:', mark.greet());
  console.log('Person:', mark.greet('Nathalie'));

  var angryMark = new AngryPerson('Mark');
  console.log('AngryPerson:', angryMark.greet());
  console.log('AngryPerson:', angryMark.greet('Nathalie'));
  console.log('AngryPerson instanceof Person?', angryMark instanceof Person);

More details

To create a new class, call the mojoClass function. You can pass in a variety of things:

  • The parent class to inherit from (optional)
  • A constructor (optional)
  • An object containing all of the methods and properties of the instance

Subclasses can access the methods of their parent class by calling this.super.methodName();

Thanks

Thanks for Mozilla for providing an implementation of bind for browsers that don't support it, and John Resig for his Simple JavaScript Inheritance post, which reminded me of the instanceof operator.

Randomly...

I didn't set out to write a particularly small implementation when I started, but out of curiosity, I poked around a bit to see how mojo compared. If you're looking for something positively tiny, John Resig's Simple JavaScript Inheritance is only 25 lines of code. Eep!

About

A small, simple implementation of traditional classes and inheritance for JavaScript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published