JavaScript With Class

[edit: I looked through the Class implementation in prototype.js. It looks like I’m on the right track.]

In an effort to learn some JavaScript, I wrote a simple function to construct classes. It just does inheritance right now. The only minor convenience is it uses the Functional library to make it easier to write short methods. Here’s an example using my class system:

var Stack = Class(Object, {
    initialize: function() { this.data = []; },
    push      : 'this.data.push(e)',
    pop       : 'this.data.pop()'
});

var Queue = Class(Stack, {
    pop : 'this.data.shift()'
});

var Deck = Class(Stack, {
    initialize: function () {
	for (var v=2; v < 15; v++)
	    for (var s=0; s < suits.length; s++)  		this.push([suits[s],v]) ;     },      shuffle   : function () {     var cards = this.data 	for (var i=cards.length-1; i >= 0; i--) {
	    var r = random(i+1) ;
	    var tmp = cards[i] ;
	    cards[i] = cards[r] ;
	    cards[r] = tmp ;
	}
    },
    deal      : 'this.pop()'
});

Here’s my implementation:

function Class(parent, members) {
    // parent is optional, defaults to Object
    if (typeof(parent) != 'string' && typeof(members) == 'undefined' ) {
	members = parent ;
	parent = 'Object' ;
    }

    // Set a default empty initializer
    if (typeof(members.initialize) == 'undefined') {
	members.initialize = function(){} ;
    }

    // The constructor must call the parent's constructor
    var constructor = function() {
	parent.apply(this, arguments) ;
	members.initialize.apply(this, arguments) ;
    }

    constructor.prototype = new parent ;

    // Assign the members, convert strings to functions
    for (var member in members) {
	var func = members[member] ;
	if (typeof(func) == 'string')
	    func = func.lambda() ;
	constructor.prototype[member] = func ;
    }
    return constructor ;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s