Skip to content

Instantly share code, notes, and snippets.

@markandrus
Last active August 29, 2015 14:04
Show Gist options
  • Save markandrus/4dbd83116cd3c0169659 to your computer and use it in GitHub Desktop.
Save markandrus/4dbd83116cd3c0169659 to your computer and use it in GitHub Desktop.
class.sjs
// Class Macro with Support for Inheritance
// ========================================
macro class {
rule { $className($cparam:ident (,) ...) { $cbody } } => {
function $className($cparam (,) ...) {
if (!(this instanceof $className)) {
return new $className($cparam (,) ...);
}
$cbody ...
}
}
rule { $className($cparam:ident (,) ...) extends $superClass:ident (,) ... { $cbody ... } } => {
function $className($cparam (,) ...) {
if (!(this instanceof $className)) {
return new $className($cparam (,) ...);
}
$($superClass.call(this);) ...
$cbody ...
}
(function(inherits) {
$(inherits($className, $superClass);) ...
}(require('util').inherits));
}
}
// Example: Extending EventEmitter
// -------------------------------
var EventEmitter = require('events').EventEmitter;
class Person(name) extends EventEmitter {
Object.defineProperty(this, 'name', {
value: name
});
}
Person.prototype.say = function(something) {
this.emit('say', this.name + ' said, "' + something + '"');
};
var bob = new Person('Bob');
bob.on('say', function(something) { console.log(something); });
bob.say('Hello world!');
/*
$ sjs -r --format-indent=2 class.sjs
// Example: Extending EventEmitter
// -------------------------------
var EventEmitter = require('events').EventEmitter;
function Person(name) {
if (!(this instanceof Person)) {
return new Person(name);
}
EventEmitter.call(this);
Object.defineProperty(this, 'name', { value: name });
}
(function (inherits) {
inherits(Person, EventEmitter);
}(require('util').inherits));
Person.prototype.say = function (something) {
this.emit('say', this.name + ' said, "' + something + '"');
};
var bob = new Person('Bob');
bob.on('say', function (something) {
console.log(something);
});
bob.say('Hello world!');
$ sjs -r --format-indent=2 class.sjs | node
Bob said, "Hello world!"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment