1
0
Fork 0

Class constructors are now self-invoking

- Permits omitting 'new' keyword, which is a style preferred by some (such as Crockford)
- It's very difficult to use apply() with the 'new' keyword - this method permits a simple way of passing an argument list to the constructor
closure/master
Mike Gerwitz 2010-12-28 19:05:53 -05:00
parent 76423fc4ea
commit 44186068b4
2 changed files with 33 additions and 2 deletions

View File

@ -165,8 +165,17 @@ var extend = ( function( extending )
// concrete class // concrete class
if ( abstract_methods.length === 0 ) 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(); this.__initProps();
// call the constructor, if one was provided // 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 // note that since 'this' refers to the new class (even
// subtypes), and since we're using apply with 'this', the // subtypes), and since we're using apply with 'this', the
// constructor will be applied to subtypes without a problem // constructor will be applied to subtypes without a problem
this.__construct.apply( this, arguments ); this.__construct.apply( this, ( args || arguments ) );
args = null;
} }
}; };
} }

View File

@ -126,3 +126,24 @@ assert.ok(
"Parent constructor sets values on subtype" "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"
);