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 constructorclosure/master
parent
76423fc4ea
commit
44186068b4
14
lib/class.js
14
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;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
|
@ -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"
|
||||
);
|
||||
|
||||
|
|
Loading…
Reference in New Issue