Class.js

Posted under JavaScript on May 8, 2010.

Table of Contents

Comment

See what others have to say on this topic, or add your own two cents.

Overview

JavaScript by nature does not have classes like other languages. This has been a source of frustration for developers trying to create complex applications. Class.js attempts to provide the JavaScript language with a basic class structure in under a kilobyte of code.

Download

Create A Class

One = {
	
	message:'',
	
	set:function(val){
	
		this.message = val;
	
	},
	
	get:function(){
	
		alert(this.message);
	
	}

};

Using Your Class

var e = new Class(One);
e.set('Hello, World!');
e.get();

Constructors

If it exists, the method construct(), will be called when you instantiate the class. The constructor may have arguments.

One = {
	
	message:'',
	
	construct:function(val){
	
		this.set(val);
	
	},
	
	set:function(val){
	
		this.message = val;
	
	},
	
	get:function(){
	
		alert(this.message);
	
	}

};

Usage:

var e = new Class(One,['Awesome!']);
e.get();

Extending Classes

By using the Extend() function, you can create extensions of currently existing classes.

One = {

	message:'',
	
	set:function(val){
	
		this.message = val;
	
	},
	
	get:function(){
	
		alert(this.message);
	
	}

};

Two = Extend(One,{

	construct:function(val){
	
		this.set(val);
	
	}

});

Usage

var e = new Class(Two,['Quixotic!']);
e.get();

Note that you can not override existing methods when extending a class.

Class.merge()

merge() is a method that is built right into all classes you create. It essentially allows you to extend an instance of a class.

One = {

	message:'',
	
	set:function(val){
	
		this.message = val;
	
	}

};

Usage:

var e = new Class(One);
e.merge({

	get:function(){
	
		alert(this.message);
	
	}

});

e.set('Fabtasic!');
e.get();

Plugins

You can create your own methods, just like Class.merge(), by simply adding it to the ClassFn object.

ClassFn.whatever = function(){

	// ...

});

Usage:

var e = new Class({});
e.whatever();

GPL License

This script is licensed under the General Public License.