Skip to content

Instantly share code, notes, and snippets.

@CrabDude
Created February 10, 2011 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrabDude/821279 to your computer and use it in GitHub Desktop.
Save CrabDude/821279 to your computer and use it in GitHub Desktop.
Pvt.js - JavaScript Private Instance Members
/* Pvt.js - JavaScript Private Instance Members
* By Adam Crabtree http://noderiety.com/
* MIT Licensed.
*/
/**
* Generate a private member store
* @returns {function} The private member accessor function
*/
function Pvt() {
// Lookup array for storing private member objects
var store = [];
/**
* The private member accessor function
* @param {object} The lookup object
* @returns {object} The object's associated private member store
*/
return function(obj) {
// initialize the object's store
if (typeof obj._pvt == 'undefined') {
/* REVISION #1 (See Below for Comments)
obj._pvt = store.push({_self : obj})-1;
REVISION #2
// Generate random key
while((_pvt += chars.charAt(Math.floor(Math.random() * 62))).length < 6);
obj._pvt = {key: store.push({_pvt : _pvt})-1, hash: _pvt};
*/
obj._pvt = store.push({})-1;
}
/* REVISION #1
// Ensure we have with the original object, not just an equivalent ._pvt
return store[obj._pvt]._self === obj ? store[obj._pvt] : null;
=> Creates memory leak preventing obj from being garbage collected
=> Only fail-proof way to prevent object impersonation
REVISION #2
// Ensure object fingerprints match
return store[obj._pvt.key]._pvt === obj._pvt.hash ? store[obj._pvt.key] : null;
=> Significantly decreases performance
=> Not fail-proof, but very difficult to fake
*/
return store[obj._pvt];
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment