Added support for extending classes via convenience method and tests for property inheritance
parent
c42598c47b
commit
909542d19b
41
lib/class.js
41
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,
|
||||
} );
|
||||
}
|
||||
|
|
|
@ -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
|
||||
);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue