Last active
August 29, 2015 14:04
-
-
Save markandrus/4dbd83116cd3c0169659 to your computer and use it in GitHub Desktop.
class.sjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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