1
0
Fork 0

Added support for extending classes via convenience method and tests for property inheritance

closure/master
Mike Gerwitz 2010-11-10 21:10:31 -05:00
parent c42598c47b
commit 909542d19b
2 changed files with 59 additions and 23 deletions

View File

@ -82,6 +82,7 @@ var extend = function()
prop_copy( props, prototype ); prop_copy( props, prototype );
// set up the new class // set up the new class
attach_extend( new_class );
new_class.prototype = prototype; new_class.prototype = prototype;
new_class.constructor = new_class; new_class.constructor = new_class;
@ -103,25 +104,27 @@ exports.extend = function( base )
} }
/** var attach_extend = function( func )
* 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',
{ {
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 ); value: function( props )
}, {
return extend( this, props );
enumerable: false, },
writable: false,
configurable: false,
} );
enumerable: false,
writable: false,
configurable: false,
} );
}

View File

@ -25,11 +25,44 @@ require( './common' );
var assert = require( 'assert' ), var assert = require( 'assert' ),
Class = require( 'class' ); Class = require( 'class' );
var Foo = Class.extend(); var foo_props = {
one: 1,
two: 2,
},
Foo = Class.extend( foo_props );
assert.ok( assert.ok(
( Foo.prototype.extend instanceof Function ), ( Foo.extend instanceof Function ),
"Created class contains extend method in prototype" "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
);
}