diff --git a/lib/class.js b/lib/class.js index 4f426a8..a307f13 100644 --- a/lib/class.js +++ b/lib/class.js @@ -165,8 +165,17 @@ var extend = ( function( extending ) // concrete class if ( abstract_methods.length === 0 ) { - return function() + var args = null; + return function __self() { + if ( !( this instanceof __self ) ) + { + // store arguments to be passed to constructor and + // instantiate new object + args = arguments; + return new __self(); + } + this.__initProps(); // call the constructor, if one was provided @@ -175,7 +184,8 @@ var extend = ( function( extending ) // note that since 'this' refers to the new class (even // subtypes), and since we're using apply with 'this', the // constructor will be applied to subtypes without a problem - this.__construct.apply( this, arguments ); + this.__construct.apply( this, ( args || arguments ) ); + args = null; } }; } diff --git a/test/test-class-constructor.js b/test/test-class-constructor.js index 86f7db2..c39dcf9 100644 --- a/test/test-class-constructor.js +++ b/test/test-class-constructor.js @@ -126,3 +126,24 @@ assert.ok( "Parent constructor sets values on subtype" ); + +var subobj2 = SubFoo( args2[ 0 ], args2[ 1 ] ); + +assert.ok( + ( subobj2 instanceof SubFoo ), + "Constructor is self-invoking" +); + +assert.equal( + construct_context, + subobj2, + "Self-invoking constructor is run in the context of the new object" +); + +assert.ok( + ( ( subobj2.args[ 0 ] === args2[ 0 ] ) + && ( subobj2.args[ 1 ] == args2[ 1 ] ) + ), + "Self-invoking constructor receives arguments" +); +