Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

Add a class_compat layer for easy access to traditional classes.

  • Loading branch information...
commit 24a4ae5364db6f4bc576154c609ca78dd4fc971c 1 parent e23f7ad
@creationix authored
Showing with 33 additions and 0 deletions.
  1. +4 −0 lib/class.js
  2. +29 −0 lib/class_compat.js
4 lib/class.js
@@ -4,6 +4,10 @@ var Class = module.exports = Object.create(Object.prototype, {
// Implement extend for easy prototypal inheritance
extend: {value: function extend(obj) {
if (obj === undefined) return Object.create(this);
+ // Hook back so the constructor function still works like classical if needed
+ if (typeof obj.constructor === 'function') {
+ Object.defineProperty(obj.constructor, "prototype", {value: obj});
+ }
obj.__proto__ = this;
Object.freeze(obj); // Lock the prototype to enforce no changes
return obj;
29 lib/class_compat.js
@@ -0,0 +1,29 @@
+var Class = require('./class');
+// This global modifier allows you to treat constructor based classes as if
+// they were prototype based.
+// Define an extend method for constructor functions that works like prototype extends.
+Object.defineProperty(Function.prototype, "extend", {value: function extend(obj) {
+ // Clone the functions's prototype
+ var props = {}, proto = this.prototype;
+ Object.getOwnPropertyNames(proto).forEach(function (key) {
+ props[key] = Object.getOwnPropertyDescriptor(proto, key);
+ });
+ // Put the constructor on a prop too
+ props.constructor = {value: this};
+ // Make obj's parent be an Classy version of props
+ if (obj === undefined) return Object.create(Class, props);
+ obj.__proto__ = Object.create(Class, props);
+ Object.freeze(obj);
+ return obj;
+// This is the "new" keyword implemented in pure ES5
+Object.defineProperty(Function.prototype, "new", {value: function () {
+ var obj = Object.create(this.prototype, {constructor: this});
+ var result = this.apply(obj, arguments);
+ return result === undefined ? obj : result;

1 comment on commit 24a4ae5


I think this is not needed at all, but if you need it, I'd do it other way round - not copy the function's prototype and connect it to Class framework, but Objct.create() from the original function's prototype and extend it with Class framework stuff. It's much more safe and dynamic (reacts to changes made in original prototype in the run time).

But, personally, I do not see any need for any "Class" framework and old-school splitting the world between classes with behaviour and instances with state. Javascript is very powerful with its prototypal model, so use it as it was intended (only helper I would use are ones who stramline the clumsy (Subclass.prototype = Object.create(Superclass.prototype)), eventually ones who fill the prototype with content, so one does not need to write = function () {.... But as I said, that's my personal feeling.

Please sign in to comment.
Something went wrong with that request. Please try again.