Permalink
Browse files

Add a class_compat layer for easy access to traditional classes.

  • Loading branch information...
1 parent e23f7ad commit 24a4ae5364db6f4bc576154c609ca78dd4fc971c @creationix committed Aug 19, 2010
Showing with 33 additions and 0 deletions.
  1. +4 −0 lib/class.js
  2. +29 −0 lib/class_compat.js
View
@@ -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;
View
@@ -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;
+}});

0 comments on commit 24a4ae5

Please sign in to comment.