1
0
Fork 0

FallbackSymbol now returns instance of self

Existing functionality is maintained using toString. This is necessary to
support type checking, and to be more consistent with the native Symbol
implementation.

Technically `new FallbackSymbol` is supposed to throw a TypeError, just as
`new Symbol` would, but doing so complicates the constructor unncessarily,
so I am not going to bother with that here.
protolib
Mike Gerwitz 2014-07-09 23:50:36 -04:00
parent 07c0a974af
commit d400a4cbb1
2 changed files with 28 additions and 6 deletions

View File

@ -58,9 +58,31 @@ var _root = ' ' + String.fromCharCode(
*/ */
function FallbackSymbol() function FallbackSymbol()
{ {
return _root + _floor( _random() * 1e8 ); if ( !( this instanceof FallbackSymbol ) )
{
return new FallbackSymbol();
}
this.___$$id$$ = ( _root + _floor( _random() * 1e8 ) );
} }
FallbackSymbol.prototype = {
/**
* Return random identifier
*
* This is convenient, as it allows us to both treat the symbol as an
* object of type FallbackSymbol and use the symbol as a key (since
* doing so will automatically call this method).
*
* @return {string} random identifier
*/
toString: function()
{
return this.___$$id$$;
},
};
module.exports = FallbackSymbol; module.exports = FallbackSymbol;

View File

@ -33,14 +33,14 @@ require( 'common' ).testCase(
* to the holder of a reference to the symbol used to create that field. * to the holder of a reference to the symbol used to create that field.
* Since this fallback is intended to be used in environments that do * Since this fallback is intended to be used in environments that do
* not support symbols, the alternative is to return a random string * not support symbols, the alternative is to return a random string
* that is highly unlikely to exist in practice. * that is highly unlikely to exist in practice. However, we must also
* return an object to allow for instanceof checks. See below test for
* more details.
*/ */
'Constructor returns a generated string': function() 'Constructor returns an instance of Symbol': function()
{ {
var result = this.Sut(); var result = this.Sut();
this.assertOk( result instanceof this.Sut );
this.assertOk( typeof result === 'string' );
this.assertOk( result.length > 0 );
}, },