1
0
Fork 0

Tada! Private members.

closure/master
Mike Gerwitz 2011-03-06 23:03:39 -05:00
parent c1765cd720
commit 30bfde50cd
2 changed files with 36 additions and 2 deletions

View File

@ -33,7 +33,8 @@ var util = require( './util' ),
exports.setup = function( base, dest, properties, members ) exports.setup = function( base, dest, properties, members )
{ {
var prop_pub = properties[ 'public' ], var prop_pub = properties[ 'public' ],
prop_prot = properties[ 'protected' ] prop_prot = properties[ 'protected' ],
prop_priv = properties[ 'private' ]
; ;
// initialize each of the properties for this instance to // initialize each of the properties for this instance to
@ -46,6 +47,7 @@ exports.setup = function( base, dest, properties, members )
} }
var methods_protected = members[ 'protected' ], var methods_protected = members[ 'protected' ],
methods_private = members[ 'private' ],
hasOwn = Array.prototype.hasOwnProperty hasOwn = Array.prototype.hasOwnProperty
; ;
@ -57,12 +59,23 @@ exports.setup = function( base, dest, properties, members )
dest[ method_name ] = methods_protected[ method_name ]; dest[ method_name ] = methods_protected[ method_name ];
} }
} }
for ( method_name in methods_private )
{
if ( hasOwn.call( methods_private, method_name ) )
{
dest[ method_name ] = methods_private[ method_name ];
}
}
// initialize protected properties and store in instance data // initialize private/protected properties and store in instance data
for ( prop in prop_prot ) for ( prop in prop_prot )
{ {
dest[ prop ] = util.clone( prop_prot[ prop ] ); dest[ prop ] = util.clone( prop_prot[ prop ] );
} }
for ( prop in prop_priv )
{
dest[ prop ] = util.clone( prop_priv[ prop ] );
}
}; };

View File

@ -199,3 +199,24 @@ var common = require( './common' ),
); );
} )(); } )();
/**
* Private members should be accessible from within class methods
*/
( function testPrivateMembersAreAccessibleInternally()
{
assert.equal(
foo.getProp( 'parts' ),
priv,
"Private properties are available internally"
);
// invoke rather than checking for equality, because the method may be
// wrapped
assert.equal(
foo.getProp( 'privf' )(),
priv,
"Private methods are available internally"
);
} )();