JavaScript "uso estricto"


Tabla de contenido

    Mostrar tabla de contenidos


"use estricto"; Define que El código JavaScript debe ejecutarse en "Modo estricto".


La directiva de "uso estricto"

La directiva "use estricto" era nueva en ECMAScript versión 5.

No es una declaración, sino una expresión literal, ignorada por versiones anteriores. de JavaScript.

El propósito de "use estricto" es indicar que el código debe ejecutarse en "modo estricto".

Con el modo estricto, no puede, por ejemplo, utilizar variables no declaradas.

Todos los navegadores modernos admiten el "uso estricto", excepto Internet Explorer 9 y versiones anteriores:

Directive
"use strict" 13.0 10.0 4.0 6.0 12.1

Los números de la tabla especifican la primera versión del navegador que es totalmente compatible con la directiva.

Puede utilizar el modo estricto en todos sus programas. Te ayuda a escribir código más limpio, como impedirle utilizar variables no declaradas.

"use estricto" es solo una cadena, por lo que IE 9 no generará un error incluso si no lo comprende.


Declarar modo estricto

El modo estricto se declara agregando "use estricto"; al comienzo de un script o una función.

Declarado al comienzo de un script, tiene alcance global (todo el código en el script se ejecutará en modo estricto):

Ejemplo

"use strict";
x = 3.14;       // This will cause an error 
 because x is not declared

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Using a variable without declaring it, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
x = 3.14;  // This will cause an error (x is not defined).
</script>

</body>
</html>

Ejemplo

"use strict";
myFunction();

function myFunction() {
   y = 3.14;   // This will also cause an error 
 because y is not declared
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>Global "use strict" declaration.</h2>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
myFunction();

function myFunction() {
  y = 3.14;   // This will cause an error (y is not defined)
}
</script>

</body>
</html>

Declarado dentro de una función, tiene alcance local (solo el código dentro de la función es en modo estricto):

x = 3.14;       // This will not cause an error.
 
myFunction();
function 
 myFunction() {
  "use strict";
    y = 3.14;   // This will cause an error
}

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<p>"use strict" in a function will only cause errors in that function.</p>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
x = 3.14;    // This will not cause an error.
myFunction();

function myFunction() {
  "use strict";
  y = 3.14;  // This will cause an error (y is not defined).
}
</script>

</body>
</html>


El “uso estricto”; Sintaxis

La sintaxis, para declarar el modo estricto, fue diseñada para ser compatible con versiones anteriores de JavaScript.

Compilando un literal numérico (4 + 5;) o un literal de cadena ("John Doe";) en un El programa JavaScript no tiene efectos secundarios. Simplemente se compila en un archivo no existente. variable y muere.

Entonces "use estricto"; sólo importa a los nuevos compiladores que "entienden" el significado de ello.


¿Por qué el modo estricto?

El modo estricto facilita la escritura de JavaScript "seguro".

El modo estricto convierte la "mala sintaxis" previamente aceptada en errores reales.

Por ejemplo, en JavaScript normal, escribir mal el nombre de una variable crea una nueva variable global. En modo estricto, esto arrojará un error, haciendo imposible crear accidentalmente una variable global.

En JavaScript normal, un desarrollador no recibirá ningún comentario de error. asignar valores a propiedades no modificables.

En modo estricto, cualquier asignación a una propiedad no grabable, un getter-only propiedad, una propiedad inexistente, una variable inexistente o una variable inexistente objeto, arrojará un error.


No permitido en modo estricto

No se permite utilizar una variable sin declararla:

"use strict";
 x = 3.14;                // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Using a variable without declaring it, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
x = 3.14;  // This will cause an error (x is not defined).
</script>

</body>
</html>

Los objetos también son variables.

No está permitido utilizar un objeto, sin declararlo:

"use strict";
 x = {p1:10, p2:20};      // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Using an object without declaring it, is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
x = {p1:10, p2:20};   // This will cause an error (x is not defined).
</script>

</body>
</html>

No se permite eliminar una variable (u objeto).

"use strict";
let x = 3.14;
delete x;                // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With &quot;use strict&quot;:</h2>
<h3>Deleting a variable (or object) is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
let x = 3.14;
delete x;     // This will cause an error 
</script>

</body>
</html>

No se permite eliminar una función.

"use strict";
function x(p1, p2) {}; 
delete x;                
 // This will cause an error 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Deleting a function is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
function x(p1, p2) {}; 
delete x;        // This will cause an error 
</script>

</body>
</html>

No se permite duplicar el nombre de un parámetro:

"use strict";
function x(p1, p1) {};   // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Duplicating a parameter name is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
function x(p1, p1) {};   // This will cause an error 
</script>

</body>
</html>

No se permiten literales numéricos octales:

"use strict";
let x = 010;             // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Octal numeric literals are not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
let x = 010;   // This will cause an error 
</script>

</body>
</html>

No se permiten caracteres de escape octal:

"use strict";
let x = "\010";            // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Octal escape characters are not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
let x = "\010";   // This will cause an error 
</script>

</body>
</html>

No se permite escribir en una propiedad de solo lectura:

"use strict";
const obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

obj.x = 3.14;            // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Writing to a read-only property is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
const obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

obj.x = 3.14;   // This will cause an error
</script>

</body>
</html>

No se permite escribir en una propiedad de solo obtención:

"use strict";
const obj = {get x() 
{return 0} };
obj.x = 3.14;            // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Writing to a get-only property is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
const obj = {get x() {return 0} };

obj.x = 3.14;   // This will cause an error
</script>

</body>
</html>

No se permite eliminar una propiedad no eliminable:

"use strict";
delete Object.prototype; // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Deleting an udeletable property is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
delete Object.prototype;   // This will cause an error 
</script>

</body>
</html>

La palabra eval no se puede utilizar como variable:

"use strict";
let eval = 3.14;         // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>The string "eval" cannot be used as a variable.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
let eval = 3.14;   // This will cause an error 
</script>

</body>
</html>

La palabra argumentos no se puede utilizar como variable:

"use strict";
let arguments = 3.14;    // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>The string "arguments" cannot be used as a variable.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
let arguments = 3.14;   // This will cause an error 
</script>

</body>
</html>

La declaración with no está permitida:

"use strict";
with (Math){x = cos(2)}; // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>The with statement is not allowed.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
with (Math){x = cos(2)};   // This will cause an error 
</script>

</body>
</html>

Por razones de seguridad, eval() no puede crear variables en el ámbito desde el que se llamó.

En modo estricto, una variable no se puede utilizar antes de declararla:

"use strict";
eval ("x = 2");
alert (x);      // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>For security reasons, eval() is not allowed to create variables in the scope from which it was called.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
eval ("x = 2");
alert (x);      // This will cause an error 
</script>

</body>
</html>

En modo estricto, eval() no puede declarar una variable usando la palabra clave var:

"use strict";
eval ("var x = 2");
alert (x);    // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>For security reasons, eval() is not allowed to create variables in the scope from which it was called.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
eval ("var x = 2");
alert (x);      // This will cause an error 
</script>

</body>
</html>

eval() no puede declarar una variable usando la palabra clave let:

eval ("let x = 2");
alert (x);        // This 
will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>Using eval()</h2>
<h3>For security reasons, eval() is not allowed to create variables in the scope from which it was called.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
eval ("let x = 2");
alert (x);      // This will cause an error 
</script>

</body>
</html>

La palabra clave this en funciones se comporta de manera diferente en modo estricto.

La palabra clave this se refiere al objeto que llamada la función.

Si no se especifica el objeto, funciona en modo estricto. devolverá undefinido y funciona normalmente El modo devolverá el objeto global (ventana):

"use strict";
function myFunction() {
  
  alert(this); // will alert "undefined"
}
myFunction(); 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Inside functions, the "this" keyword is no longer the global object if not specified:</h3>

<script>
"use strict";
function myFunction() {
  alert(this);
}
myFunction();
</script>

</body>
</html>

¡Prueba del futuro!

Las palabras clave reservadas para futuras versiones de JavaScript NO se pueden utilizar como variables nombres en modo estricto.

Estos son:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield
"use strict";
let public = 1500;      // This will cause an error

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>With "use strict":</h2>
<h3>Future reserved keywords are not allowed in strict mode.</h3>

<p>Activate debugging in your browser (F12) to see the error report.</p>

<script>
"use strict";
let public = 1500;   // This will cause an error 
</script>

</body>
</html>

¡Cuidado!

La directiva "use estricto" sólo se reconoce al comienzo de un script o una función.