// . // . , // , . var safeCache = Object.create(null); // , - . ["hasOwnProperty", "toString", "valueOf", "constructor", "__proto__"] .forEach( function iterator(key, index) { console.log("[ %s ] exists: %s", key, ( key in safeCache )); } );
[ hasOwnProperty ] exists: false [ toString ] exists: false [ valueOf ] exists: false [ constructor ] exists: false [ __proto__ ] exists: true
// // null, , , // . 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__")); // , // // , , . 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__"));
Source: https://habr.com/ru/post/253051/
All Articles