From 909542d19b283a991d76b0cb2c26884b838e41f2 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Wed, 10 Nov 2010 21:10:31 -0500 Subject: [PATCH] Added support for extending classes via convenience method and tests for property inheritance --- lib/class.js | 41 +++++++++++++++++++++------------------ test/test-class-extend.js | 41 +++++++++++++++++++++++++++++++++++---- 2 files changed, 59 insertions(+), 23 deletions(-) diff --git a/lib/class.js b/lib/class.js index 3908351..3e458b1 100644 --- a/lib/class.js +++ b/lib/class.js @@ -82,6 +82,7 @@ var extend = function() prop_copy( props, prototype ); // set up the new class + attach_extend( new_class ); new_class.prototype = prototype; new_class.constructor = new_class; @@ -103,25 +104,27 @@ exports.extend = function( base ) } -/** - * 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, 'extend', +var attach_extend = function( func ) { - value: function( props ) + /** + * 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( func, 'extend', { - return extend( this, props ); - }, - - enumerable: false, - writable: false, - configurable: false, -} ); + value: function( props ) + { + return extend( this, props ); + }, + enumerable: false, + writable: false, + configurable: false, + } ); +} diff --git a/test/test-class-extend.js b/test/test-class-extend.js index 3ac9e51..be862ef 100644 --- a/test/test-class-extend.js +++ b/test/test-class-extend.js @@ -25,11 +25,44 @@ require( './common' ); var assert = require( 'assert' ), Class = require( 'class' ); -var Foo = Class.extend(); - +var foo_props = { + one: 1, + two: 2, + }, + Foo = Class.extend( foo_props ); assert.ok( - ( Foo.prototype.extend instanceof Function ), - "Created class contains extend method in prototype" + ( Foo.extend instanceof Function ), + "Created class contains extend method" ); +var sub_props = { + three: 3, + four: 4, + }, + SubFoo = Foo.extend( sub_props ); + +assert.ok( + ( SubFoo instanceof Object ), + "Subtype is returned as an object" +); + +// ensure properties were inherited from supertype +for ( var prop in foo_props ) +{ + assert.equal( + foo_props[ prop ], + SubFoo.prototype[ prop ], + "Subtype inherits parent properties: " + prop + ); +} + +// and ensure that the subtype's properties were included +for ( var prop in sub_props ) +{ + assert.equal( + sub_props[ prop ], + SubFoo.prototype[ prop ], + "Subtype contains its own properties: " + prop + ); +}