diff --git a/lib/class_builder.js b/lib/class_builder.js index 171a57e..e1757f2 100644 --- a/lib/class_builder.js +++ b/lib/class_builder.js @@ -327,6 +327,14 @@ function createConcreteCtor( cname, members ) initInstance( instance_id, this ); this.__initProps(); + // If we're extending, we don't actually want to invoke any class + // construction logic. The above is sufficient to use this class in a + // prototype, so stop here. + if ( extending ) + { + return; + } + // call the constructor, if one was provided if ( this.__construct instanceof Function ) { diff --git a/test/test-class-extend.js b/test/test-class-extend.js index 29aa3fd..40c3796 100644 --- a/test/test-class-extend.js +++ b/test/test-class-extend.js @@ -348,3 +348,28 @@ for ( var i = 0; i < class_count; i++ ) }, Error, "Cannot redeclare method in same class definition" ); } )(); + +/** + * To understand this test, one must understand how "inheritance" works + * with prototypes. We must create a new instance of the ctor (class) and add + * that instance to the prototype chain (if we added an un-instantiated + * constructor, then the members in the prototype would be accessible only + * though ctor.prototype). Therefore, when we instantiate this class for use in + * the prototype, we must ensure the constructor is not invoked, since our + * intent is not to create a new instance of the class. + */ +( function testConstructorShouldNotBeCalledWhenExtendingClass() +{ + var called = false, + Foo = Class( { + 'public __construct': function() + { + called = true; + } + } ).extend( {} ); + + assert.equal( called, false, + "Constructor should not be called when extending a class" + ); +} )(); +