diff --git a/lib/util.js b/lib/util.js index 7cb42d0..97bd0ca 100644 --- a/lib/util.js +++ b/lib/util.js @@ -150,7 +150,9 @@ exports.clone = function clone( data, deep ) // support toSource(), they'd still do the same damn thing. return data; } - else if ( typeof data === 'object' ) + // explicitly testing with instanceof will ensure we're actually testing an + // object, not something that may be misinterpreted as one (e.g. null) + else if ( data instanceof Object ) { var newobj = {}, hasOwn = Object.prototype.hasOwnProperty; diff --git a/test/test-util-clone.js b/test/test-util-clone.js index cf8b649..fc2efa0 100644 --- a/test/test-util-clone.js +++ b/test/test-util-clone.js @@ -119,3 +119,27 @@ for ( var prop in deep_obj ) ); } )(); + +/** + * Primitives cannot be cloned, so we should expect that they are simply + * returned + */ +( function testPrimitivesAreProperlyReturnedByClone() +{ + // we don't try NaN because NaN != NaN; we'll try it separately + var prim = [ null, 1, true, false, undefined ], + i = prim.length; + + while ( i-- ) + { + var val = prim[ i ]; + + assert.equal( val, util.clone( val ), + 'Failed to clone primitive value: ' + val + ); + } + + // test NaN separately + assert.ok( isNaN( util.clone( NaN ) ) ); +} )(); +