From 8d6c2645bc96540caf41d58d43d9de09aaf41d8c Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Wed, 10 Nov 2010 18:40:36 -0500 Subject: [PATCH] Began adding Class.extend() --- lib/class.js | 57 +++++++++++++++++++++++++++++++++++++++------- test/test-class.js | 14 ++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/lib/class.js b/lib/class.js index d890e87..5449b01 100644 --- a/lib/class.js +++ b/lib/class.js @@ -31,21 +31,62 @@ var Class = function() }; -exports.extend = function() +/** + * Mimics class inheritance + * + * This method will mimic inheritance by setting up the prototype with the + * provided base class (or, by default, Class) and copying the additional + * properties atop of it. + * + * The class to inherit from (the first argument) is optional. If omitted, the + * first argument will be considered to be the properties list. + * + * @return {Object} extended class + */ +var extend = function() { - Class.prototype.extend.apply( this, arguments ); + var args = Array.prototype.slice.call( arguments ), + props = args.pop() || {}, + base = args.pop() || Class, + + prototype = new base(), + new_class = function() {}; + + new_class.prototype = prototype; + + return new_class; } +/** + * Creates a class, inheriting either from the provided base class or the + * default base class + * + * @param {Object} base object to extend (extends Class by default) + * + * @return {Object} extended class + */ +exports.extend = function( base ) +{ + return extend.apply( this, arguments ); +} + + +/** + * Shorthand for extending classes + * + * This method can be invoked on the object, rater than having to call + * Class.extend( this ). + * + * @param {Object} props properties to add to extended class + * + * @return {Object} extended class + */ Object.defineProperty( Class.prototype, 'extend', { - value: function() + value: function( props ) { - var args = Array.prototype.slice.call( arguments ), - props = args.pop() || {}, - base = args.pop() || Class; - - var prototype = new this(); + return extend( this, props ); }, enumerable: false, diff --git a/test/test-class.js b/test/test-class.js index 98c81c8..2c8c35b 100644 --- a/test/test-class.js +++ b/test/test-class.js @@ -31,3 +31,17 @@ assert.ok( "Class module should provide an 'extend' method" ); + +// create a basic test class +var Foo = Class.extend(); + + +assert.ok( + ( Foo instanceof Object ), + "Extend method creates a new object" +); + +assert.ok( + ( Foo.prototype.extend instanceof Function ), + "Created class contains extend method in prototype" +);