Aquí es una API simple que usted puede disfrutar. Tiene tres funciones: Key (un constructor), KeepSecret, FetchSecret.
Lo que puede hacer es tener un objeto con un guardián secreto como propiedad. El objeto puede entonces "transportar" datos, pero el código que accede al objeto pero no conoce la clave no puede acceder a los datos ocultos.
/**
* Example usage:
*
* Create a key
*
var mykey = Key();
*
* Keep a secret
*
var mykeeper = KeepSecret(mykey, 42);
*
* Fetch the secret
*
var answer = FetchSecret(mykey, mykeeper);
*
* 'answer' will then contain 42
*/
(function(Namespace, Code) { return Code(Namespace); })(
/* Choose the namespace for Key, KeepSecret, FetchSecret */
this,
function(Namespace) {
/*
* Simply so that we can use "Key" as both a type-name
* and a parameter-name
*/
var ikey;
/** Constructor for a key */
function Key() {
if (!(this instanceof Key))
return new Key();
}
/* Same key constructor */
ikey = Key;
/**
* Hide a secret using a key
*
* @param Key
* The key to lock away the secret with
*
* @param Secret
* The secret to be locked away
*
* @return
* A function which hides the secret inside
*/
function KeepSecret(Key, Secret) {
/* The function can access itself */
var closure;
if (!(Key instanceof ikey))
throw "KeepSecret: Invalid key";
closure = function(key) {
/* If we were not passed the key, authenticate */
if (key !== Key) {
Key.keeper = closure;
return;
}
/* The caller knew the key, so reveal the secret */
return Secret;
}
return closure;
}
/**
* Use a key and a function to reveal the secret that function keeps
*
* @param Key
* The key for unlocking the secret
*
* @param Keeper
* The function keeping the secret
*
* @return
* The secret, if the key unlocks it
*/
function FetchSecret(Key, Keeper) {
/* Tracks authentication */
var closure;
if (!(Key instanceof ikey) || !(Keeper instanceof Function))
throw "FetchSecret: Invalid parameter(s)";
/* Ask the keeper to authenticate */
Keeper();
/* Note the authenticated function */
closure = Key.keeper;
/* Clear the authentication */
delete Key.keeper;
/* Did the keeper prove that they know the key? */
if (closure !== Keeper)
/* No */
return;
/* They know the key. Show we know the key, too */
return closure(Key);
}
Namespace.Key = Key;
Namespace.KeepSecret = KeepSecret;
Namespace.FetchSecret = FetchSecret;
return true;
});
Los campos privados se obtienen mediante masoquismo significativo. – biziclop
Como con la mayoría de las cosas relacionadas con JavaScript, Douglas Crockford tiene algunas [ideas sobre miembros privados] interesantes (http://www.crockford.com/javascript/private.html) en ese idioma. – maerics