Security is an issue that should not be taken lightly. Novice programmers may be unfamiliar with some of these security techniques in JavaScriptJavaScript es un lenguaje de programación que funciona en el lado del cliente y con el que las webs pueden ser más funcionales. Incorporación en código HTML El código JavaScript puede ser incrustado en las páginas HTML, para que adquieran funcionalidad. Existen varias opciones. Puede estar entre las etiquetas <SCRIPT> y </SCRIPT>, puede estar contenido en un archivo externo, puede ser un parámetro de las etiquetas HTML, y puede estar plus, e incluso uno que otro programmerConcepto de Programador¿Qué es un Programador?Un Programador es una persona, normalmente un profesional, que se encarga de escribir, de depurar y de revisar todo el código fuente de un software informático para que lleve a cabo determinadas tareas, o inclusive para que mejore, incorporando nuevas funciones para hacer que sea una herramienta más completa y eficiente.Además se le conoce como desarrollador de software, expresión que encaja estupendamente con su tarea plus experimentado puede que también ignore estas prácticas. Sin embargo, mas allá de la importancia de conocer estos métodos es praticarlos día a día en nuestra programmingConcepto de Programación¿Qué es la Programación?La Programación es el procedimiento al que se recurre para crear algún tipo de aplicación o software, para materializar un concepto o proyecto que requiere de la utilización de un lenguaje informático para poder llevarse a cabo. Es algo que está absolutamente ligado a la figura del programador, y que cada vez está cobrando más relevancia dentro del mundo del marketing.Decimos que tanto esta figura plus.

Project properties were traditionally left unprotected in JavaScript or hidden, captured in a closure. Symbols and WeakMaps offer another alternative.

Both Chrome (version 36) and Firefox (version 31) support WeakMaps. Chrome 36 supports Symbols but you need to enable Experimental JavaScript in chrome://flags/#enable-javascript-harmony. Firefox supports version 33 symbols.

Unprotected scenario

Instances of person created using the function below will have properties stored directly in them.

var Person = (function () {function Person (name) {this.name = name;} Person.prototype.getName = function () {return this.name;}; return Person;} ()); var p = new Person ('John'); print ('Person 1 name:' + p.getName ()); delete p.name; print ('Person 1 name:' + p.getName () + '- modified outside.');

This approach has the advantage that all instances of the Person they are similar and access to the properties of these instances can be optimized. But on the other hand there are no private properties here - all object properties can be modified by external code (in this case - deleted).

Several libraries prefer to prefix properties that are intended to be private with the underscore (for example, _Name).

Others - as TypeScript - dependen del compilerUn compilador es un programa que traduce código fuente escrito en un lenguaje de alto nivel como Java, a un lenguaje legible por la máquina llamado código objeto, lenguaje de destino o inclusive lenguaje ensamblador. De este modo, un compilador podría llamarse traductor, pero sus tareas son más amplias porque, como parte de la compilación del programa, además informa de errores al leer el código. Cómo funciona Un compilador siempre plus para marcar todos los usos ilegales de una propiedad privada.

Hide properties with closures

To isolate a property from an external modification, you can use an internal closure that closes over the variable name. The Douglas Crockford code conventions for JavaScript recommend this pattern when privacy is important to deter properties of names with the underscore prefix to indicate privacy.

var Person = (function () {function Person (name) {this.getName = function () {return name;};} return Person;} ()); var p = new Person ('John'); print ('Person 2 name:' + p.getName ()); delete p.name; print ('Person 2 name:' + p.getName () + 'stays private.');

The closure approach has the advantage of true privacy, but the cost is that for each instance of Person a new closure has to be created (the function within the constructor of the Person).

Use of symbols

With ES6 there is one more way to store properties: Symbols.

Symbols are similar to private names but - unlike private names - they do not provide true privacy.

Para ejecutar el ejemplo que ves tu browserUn navegador (además: browser) es una herramienta informática que te permite ver documentos y datos y navegar por la red. Los navegadores pueden mostrar distintos tipos de recursos de información; principalmente documentos HTML, a pesar de todo, además son posibles otros tipos de archivos y contenido multimedia, como PDF, JPEG, MPEG, GIF o el lenguaje de meta marcado. A través el uso de complementos especiales y la configuración respectivo, los plus debe soportar:

var Person = (function () {var nameSymbol = Symbol ('name'); function Person (name) {this [nameSymbol] = name;} Person.prototype.getName = function () {return this [nameSymbol];}; return Person;} ()); var p = new Person ('John'); print ('Person 3 name:' + p.getName ()); delete p.name; print ('Person 3 name:' + p.getName () + '- stays private.'); print ('Person 3 properties:' + Object.getOwnPropertyNames (p));

Symbols do not increase the number of closures for each instance created. There is only one clasp to protect the symbol.

Symbols are used to index JavaScript objects. The main difference with other types is that they are not converted to strings and exposed by Object.getOwnPropertyNames. Only by using the reference symbol can you set and retrieve values from the object. A list of symbols assigned to a given object can be accessed with the function Object.getOwnPropertySymbols.

Each symbol is unique, even if it was created with the same label.

ES6 Symbols ✅

var sym1 = Symbol ('a'); var sym2 = Symbol ('b'); var sym3 = Symbol ('a'); print ('sym1 === sym1:' + (sym1 === sym1)); print ('sym1 === sym2:' + (sym1 === sym2)); print ('sym1 === sym3:' + (sym1 === sym3));

Symbols have the following disadvantages:

  • Greater complexity in symbol handling - instead of a simple p.name, you have to first get the symbol reference and then use p [nameSymbol].
  • Actualmente sólo unos pocos browsersConcepto de Navegadores¿Qué son los Navegadores?Los Navegadores son herramientas informáticas que utilizamos para, normalmente, navegar por Internet y visitar cualquier página web, al mismo tiempo de para hacer otras tareas como ver documentos, observar vídeos o reproducir contenido multimedia de cualquier tipo. Son un tipo de software sencillamente usual y bastante utilizado hoy en día.Insistimos en que es algo que se utiliza con mucha frecuencia, puesto que moverse por Internet plus soportan símbolos.
  • No garantizan una verdadera privacidad, pero pueden utilizarse para separar las propiedades públicas de las internas de los objetos. Es similar a cómo la mayoría de los lenguajes orientados a objetos permiten el acceso a propiedades privadas a través de la APIConcepto de API¿Qué es una API?Una API, siglas de Application Programming Interface o Interfaz de Programación de Apps, es un recopilatorio de código que se puede emplear para que varias apps se comuniquen entre ellas. Es algo que realiza una tarea equivalente a la interfaz de usuario al momento de promover la interacción entre persona y programa, solo que aplicado única y exclusivamente dentro del entorno del software.Aún cuando suene plus de reflexión.

Private symbols are still considered for ECMAScript, but the proper implementation that never filters symbols is difficult. Private symbols are already used by the ES6 specification and implemented internally in V8.

Using WeakMaps

Another approach to storing private properties is WeakMaps.

A WeakMap instance is hidden within a closure and is indexed by instances of person. Map values are objects that contain private data.

var Person = (function () {var private = new WeakMap (); function Person (name) {var privateProperties = {name: name}; private.set (this, privateProperties);} Person.prototype.getName = function () {return private.get (this) .name;}; return Person;} ()); var p = new Person ('John'); print ('Person 4 name:' + p.getName ()); delete p.name; print ('Person 4 name:' + p.getName () + '- stays private.'); print ('Person 4 properties:' + Object.getOwnPropertyNames (p));

It is possible to use Map instead of a WeakMap or even a couple of arrays to mimic this solution. But using WeakMap has a significant advantage - it allows Person instances to be garbage collected.

A Map or a matrix holds objects that contain strongly. Person it is a closure that captures the private variable - which is also a strong reference. The garbage collector can collect an object if there are only weak references to it (or if there is no reference at all). Due to the two strong references, as long as the function Person is reachable from the CG roots, then every Person instance ever created is reachable and therefore cannot be garbage collected.

The WeakMap holds the keys weakly and that makes both the Person instance and its private data eligible for garbage collection when an object Person It is no longer referenced by the rest of the application.

Access to properties of other instances

All the solutions presented (with the exception of the closures) have an interesting feature. Instances can access private properties of other instances.

The following example classifies the instances of Person by their names. The function compareTo uses the private data of this and other instances.

var Person = (function () {var private = new WeakMap (); function Person (name) {var privateProperties = {name: name}; private.set (this, privateProperties);} Person.prototype.compareTo = function (other ) {var thisName = private.get (this) .name; var otherName = private.get (other) .name; return thisName.localeCompare (otherName);}; Person.prototype.toString = function () {return private.get (this) .name;}; return Person;} ()); var people = [new Person ('John'), new Person ('Jane'), new Person ('Jim')]; people.sort (function (first, second) {return first.compareTo (second);}); print ('Sorted people:' + people.join (','));

The same example written in Java:

import java.util.Arrays; class Person implements Comparable {private String name; public Person (String name) {this.name = name; } public int compareTo (Person other) {return this.name.compareTo (other.name); } public String toString () {return this.name; }} public class Main {public static final void main (String ... args) {Person [] people = new Person [] {new Person ("John"), new Person ("Jane"), new Person ("Jim ")}; Arrays.sort (people); System.out.print ("Sorted people:" + Arrays.toString (people)); }}

The method Person :: compareTo uses the private field name of this instance and another object.

Congratulations on completing this new tutorial, remember that on your website schoolJavaScript.com tendrás acceso a los mejores cursos de programming languageConcepto de Lenguaje de programación¿Qué es un Lenguaje de programación y qué significa?Un Lenguaje de programación es un recopilatorio de instrucciones y términos, un lenguaje formal, que se construye y se emplea para que un PC o un dispositivo pueda crear distintos tipos de datos. Por lo general, hablamos de él como el idioma que el programador habla con la máquina para crear un programa de cualquier tipo.Hay distintos clases plus JavaScript.