Skip to content

Instantly share code, notes, and snippets.

@jfhbrook
Created November 9, 2011 04:06
Show Gist options
  • Select an option

  • Save jfhbrook/1350330 to your computer and use it in GitHub Desktop.

Select an option

Save jfhbrook/1350330 to your computer and use it in GitHub Desktop.
Wherein I write a few variations on util.inherits.
var util = require("util");
// Am I the only one that finds this more readable?
// (Trailing super, return constructor)
var inherits = function (inherits, fn) {
util.inherits(fn, inherits);
return fn;
}
josh@onix:/tmp/inherits$ node
> var inherits = require("./inherits");
> var EE = require("events").EventEmitter;
>
> var FooBar = inherits(EE, function () {
... this.on("foo", function () {
... console.log("bar");
... });
... });
>
> var foobar = new FooBar;
>
> foobar.emit("foo");
bar
true
>
var util = require("util");
// This slightly beefier version can also apply your arguments through the
// whole shebang, but this might be better left to do by-hand.
// Alternately, one could use a flag to make auto-application "switch-able".
var Inherits = function (Inheritance, Constructor) {
var Inherited = function () {
Inheritance.apply(this, arguments);
Constructor.apply(this, arguments);
}
util.inherits(Inherited, Inheritance);
return Inherited;
}
// Supposing I wanted to make a "really nice" util.inherits...
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
// Do this.super_.call(this, arg2, arg2) yo'self.
// Alias prototype to proto_ for less typing
ctor.proto_ = ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
// Return the constructor
return ctor;
}
@jfhbrook
Copy link
Author

jfhbrook commented Nov 9, 2011

The jury is still out. I'll try it for a few months.

I might have to start doing that myself.

@timlind
Copy link

timlind commented Nov 9, 2011

absolutely! I think the trailing inline function is much more readable (and returning the constructor), it's how i've designed the jay library type functions. I've also got two options, one where you specify the constructor directly, and one where you define the prototype object which can optionally contain a new subconstructor. you can check it out at http://github.com/ngspinners/jay

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment