2012-07-17 12 views
7

En el lenguaje de programación Java, palabra clave privada se utiliza para ocultar datos: un campo o un método marcado como privado no está visible fuera de las clases o las subclases.Ocultación de datos en Javascript

¿Cómo se logra esto en javascript?

+6

Los campos privados se obtienen mediante masoquismo significativo. – biziclop

+1

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

Respuesta

8

En JavaScript forma estándar es utilizar diseño del módulo de como se muestra a continuación ..

var testModule = (function() { 

    var myPrivateVar = 0; 

    var myPrivateMethod = function (someText) { 
     console.log(someText); 
    }; 

    return { 

     myPublicVar: "foo", 

     myPublicFunction: function (bar) { 
      myPrivateVar++; 
      myPrivateMethod(bar); 
     } 

    }; 
})(); 

Uso: En el código anterior se devuelve un objeto que contiene una variable (myPublicVar) y una función (myPublicFunction). Dentro de esta función, puede acceder a la variable interna (myPrivateVar) y a la función interna (myPrivateMethod), pero no desde el exterior.

var mod = new testModule(); 
mod.myPublicFunction(param); 
+0

Funciona muy bien y es recomendado por el propio Douglas Crockford :) – awendt

+0

¿Puede ofrecer alguna explicación sobre lo que ocurre en su código y cómo cubre esto la ocultación de datos en javascript? Gracias – oneiros

+1

Busque "javascript closures" para comprender cómo se pueden mantener los datos lejos del alcance público. Cualquier función dentro de otra función crea un cierre. La función interna puede "recordar lo que está a su alrededor". El ejemplo anterior demuestra una función que EJECUTA INMEDIATAMENTE con(), devolviendo algunas referencias internas al nuevo objeto llamado "testModule". – Billbad

1

Todo esto logrado con el alcance.

var MYCLASS = function(){ 

    var priv_var = 0; //private var 

    this.addToVar = function(){ 
     priv_var++; 
    } 

    this.showVar = function(){ 
     return priv_var; 
    } 

} 

var mc = new MYCLASS; 

mc.addTovar(); 
alert(mc.showVar()); //"1" 
0
"use strict"; 

var Person = function (fName, lName) { 

    var firstName = fName || "AN", lastName = lName || "Other"; 

    var fullName = function() { 
     return firstName + ' ' + lastName; 
    }; 

    return { 
     setName: function (fName, lName) { 
      firstName = fName; 
      lastName = lName; 
     }, 

     getFullName: function() { 
      return fullName(); 
     } 
    }; 

} 

var p = new Person("Your", "name"); 

console.log(p.getFullName()); 
1

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; 

    }); 
Cuestiones relacionadas