“Using JS.Class” or “Sharing a Class Between Node.JS and the Browser Part 2”

Just a quick snippet, but this is a much better way of sharing a class between Node.js and the browser. I also like this psuedo Class implementation much better than the Class.js thing, it always seemed a bit ghetto how you had to say.

The ugly way (i was using this before but it felt wrong)

var ServerGame = require('./ServerGame.js').Class;

var myInstance = new ServerGame();

There’s a better way!

 * Animal.js
 * This is an example I created for us JS.Class
 * Mario Gonzalez | http://onedayitwillmake.com
var init = function()
	return new JS.Class(
		initialize: function(name) {
			this.name = name;
			console.log( 'Animal::initialize - ', name);

		 * Cause the Animal to tell you what it likes (Testing JavaDoc)
		 * @param things What the animal likes
		speak: function(things) {
			return 'My name is ' + this.name + ' and I like ' + things;

// Handle Node.JS and browser
if (typeof window === 'undefined') {
	Animal = init();
} else {
	define(['lib/jsclass/core'], init);

Ok, but now to use it in another file!

// Testing JS.Class

// bring it in

// use it
var animal = new Animal('Rex');
console.log('Animal', animal.speak("YELLING!!!") ); // Should output: Animal My name is Max and I like BARKING!!!

There you have it – so simple and soooo much cleaner!!

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.