Class (library)

Categories:Utilities

Overview

Summary

OO Class class for creating and extending JSFL/JavaScript classes

Contents

Concept

Creating classes that extend other classes in JavaScript can result in a lot of biolerplate code, so creating classes programatically can speed up this process and reduce complex code.

The xJSFL Class class is a combination of two classes created by John Resig, or jQuery fame:

Combined, this new class creates classes with both inherited properties, methods, and getters and setters.

Usage

The Class class only has one method, extend(). All classes created by Class also inherit this extend method, and so themselves can be extended by passing new properties into this method.

API

extend(prop)

Static method to create a new class, or extend an existing one

Parameters:

  • prop Object The properties to add to the class

The following example demonstrates some basic class inheritance using the Class class:

var Person = Class.extend({
	name:'',
	init: function(name) {
		this.name = name;
	},
	dance: function() {
		trace(this.name + ' dances!');
	}
});

var Ninja = Person.extend({
	init: function(name) {
		this._super(name);
	},
	dance: function() {
		return this._super(); // Call the inherited version of dance()
	},
	swingSword: function() {
		trace(this.name + ' swings sword!');
	}
});

// person
	var person = new Person('Dave');
	person.dance();

// ninja
	var ninja = new Ninja('Dave-San');
	ninja.dance();
	ninja.swingSword();

// Should all be true
	trace(person instanceof Person
	&& person instanceof Class
	&& ninja instanceof Ninja
	&& ninja instanceof Person
	&& ninja instanceof Class);
Dave dances!
Dave-San dances!
Dave-San swings sword!
true

Note that the _super() method is used to call the immediate parent's method of the same name, this simulating inheritance (albeit fairly basic).

Comments are closed.