Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 9, 2015 11:56
Show Gist options
  • Save bennadel/c3cf8fa2054fac19138e to your computer and use it in GitHub Desktop.
Save bennadel/c3cf8fa2054fac19138e to your computer and use it in GitHub Desktop.
Creating Objects With A Null Prototype In Node.js
// In this version of the cache, we're going to use an internal object with a null
// prototype and then assume that no user-provided cache keys will ever conflict with
// native keys.
function SafeCache() {
var cache = Object.create( null );
// Reveal the public API.
return({
get: get,
has: has,
remove: remove,
set: set
});
// ---
// PUBLIC METHODS.
// ---
function get( key ) {
return( cache[ key ] );
}
function has( key ) {
return( key in cache );
}
function remove( key ) {
return( delete( cache[ key ] ), this );
}
function set( key, value ) {
return( cache[ key ] = value, this );
}
}
var safeCache = new SafeCache()
.set( "foo", "Bar" )
.set( "hello", "world" )
.set( "beep", "boop" )
;
console.log( "## Safe Cache ##" );
console.log( safeCache.has( "foo" ) );
console.log( safeCache.has( "meep" ) );
console.log( safeCache.has( "valueOf" ) );
console.log( safeCache.has( "__proto__" ) );
// ---------------------------------------------------------- //
// ---------------------------------------------------------- //
// In this version of the cache, we're going to use a vanilla object and then take
// special precautions when checking for the existence of or returning a user-provided
// value.
function SaferCache() {
var cache = {};
// Reveal the public API.
return({
get: get,
has: has,
remove: remove,
set: set
});
// ---
// PUBLIC METHODS.
// ---
function get( key ) {
if ( has( key ) ) {
return( cache[ key ] );
}
}
function has( key ) {
return( cache.hasOwnProperty( key ) );
}
function remove( key ) {
return( delete( cache[ key ] ), this );
}
function set( key, value ) {
return( cache[ key ] = value, this );
}
}
var saferCache = new SaferCache()
.set( "foo", "Bar" )
.set( "hello", "world" )
.set( "beep", "boop" )
;
console.log( "## Safer Cache ##" );
console.log( saferCache.has( "foo" ) );
console.log( saferCache.has( "meep" ) );
console.log( saferCache.has( "valueOf" ) );
console.log( saferCache.has( "__proto__" ) );
// Create an object that has no prototype. This will prevent any default keys from
// existing in the object. This means that ANY and ALL keys in this object must be
// user-provided, which makes it very useful for a cache container.
var safeCache = Object.create( null );
// Let's check to see if any common Object keys exist in this object.
[ "hasOwnProperty", "toString", "valueOf", "constructor", "__proto__" ]
.forEach(
function iterator( key, index ) {
console.log( "[ %s ] exists: %s", key, ( key in safeCache ) );
}
)
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment