From d400a4cbb1b020786dfbfb14b0c26f7ba573fd9e Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Wed, 9 Jul 2014 23:50:36 -0400 Subject: [PATCH] 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. --- lib/util/symbol/FallbackSymbol.js | 24 +++++++++++++++++++++++- test/Util/symbol/FallbackSymbolTest.js | 10 +++++----- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/lib/util/symbol/FallbackSymbol.js b/lib/util/symbol/FallbackSymbol.js index ab20849..a74236a 100644 --- a/lib/util/symbol/FallbackSymbol.js +++ b/lib/util/symbol/FallbackSymbol.js @@ -58,9 +58,31 @@ var _root = ' ' + String.fromCharCode( */ 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; diff --git a/test/Util/symbol/FallbackSymbolTest.js b/test/Util/symbol/FallbackSymbolTest.js index a10aa35..21fb236 100644 --- a/test/Util/symbol/FallbackSymbolTest.js +++ b/test/Util/symbol/FallbackSymbolTest.js @@ -33,14 +33,14 @@ require( 'common' ).testCase( * 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 * 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(); - - this.assertOk( typeof result === 'string' ); - this.assertOk( result.length > 0 ); + this.assertOk( result instanceof this.Sut ); },