Modo estrito do JavaScript
- Página Anterior Hoisting JS
- Próxima Página Palavra-chave this JS
"use strict";
Define que o código JavaScript deve ser executado no "modo estrito".
Instrução "use strict"
"use strict"
É uma nova instrução no JavaScript 1.8.5 (versão ECMAScript 5).
Não é uma instrução, mas uma expressão literal, que versões mais antigas do JavaScript ignoram.
"use strict";
A função é para indicar que o código JavaScript deve ser executado no "modo estrito".
No modo estrito, você não pode, por exemplo, usar variáveis não declaradas.
Os seguintes navegadores suportam o modo estrito:
- Versões posteriores à 10 do IE
- Versões posteriores à 4 do Firefox
- Versões posteriores à 13 do Chrome
- Versões posteriores à 5.1 do Safari
- Versões posteriores à 12 do Opera
Declarar o modo estrito
Ao adicionar no início do script ou função: "use strict";
Para declarar o modo estrito.
Declarar o modo estrito no início do script, com escopo global (todos os códigos no script são executados no modo estrito):
Exemplo
"use strict"; x = 3.14; // Isso causará erro, porque x ainda não foi declarado
Exemplo
"use strict"; myFunction(); function myFunction() { y = 3.14; // Isso causará erro, porque y ainda não foi declarado }
Declarar o modo estrito dentro da função, com escopo local (apenas o código dentro da função é executado no modo estrito):
x = 3.14; // Isso não causará erro myFunction(); function myFunction() { "use strict"; y = 3.14; // Isso causará um erro }
"use strict"; sintaxe
A sintaxe do modo estrito foi projetada para ser compatível com versões mais antigas do JavaScript.
Compilar textos numéricos (por exemplo, 4+5) ou textos de string ("Bill Gates") em programas JavaScript não tem efeitos negativos. Ele só será compilado como uma variável inexistente e desaparecerá.
All "use strict";
It will only affect compilers that "understand" its meaning.
Why use strict mode?
Strict mode makes it easier to write "safe" JavaScript.
Strict mode turns previously acceptable "bad syntax" into real errors.
For example, in normal JavaScript, mistyping a variable name will create a new global variable. In strict mode, this will throw an error, so it is not possible to accidentally create a global variable.
In normal JavaScript, if you assign a value to a non-writable property, the developer will not receive any error feedback.
Assigning a value to an unwritable, read-only, non-existent property, or to a non-existent variable or object, will throw an error in strict mode.
Prohibitions in strict mode
Using a variable without declaring it is not allowed:
"use strict"; x = 3.14; // This will cause an error
An object is also a variable
Using an object without declaring it is not allowed:
"use strict"; x = {p1:10, p2:20}; // This will cause an error
Deleting a variable (or an object) is not allowed:
"use strict"; var x = 3.14; delete x; // This will cause an error
Deleting a function is not allowed:
"use strict"; function x(p1, p2) {}; delete x; // This will cause an error
Duplicate parameter names are not allowed:
"use strict"; function x(p1, p1) {}; // This will cause an error
Octal number text is not allowed:
"use strict"; var x = 010; // This will cause an error
Escape characters are not allowed:
"use strict"; var x = \010; // This will cause an error
Writing to a read-only property is not allowed:
"use strict"; var obj = {}; Object.defineProperty(obj, "x", {value:0, writable:false}); obj.x = 3.14; // This will cause an error
Writing to a property that can only be read is not allowed:
"use strict"; var obj = {get x() {return 0} }; obj.x = 3.14; // This will cause an error
Deleting non-deletable properties is not allowed:
"use strict"; delete Object.prototype; // This will cause an error
A string "eval" cannot be used as a variable:
"use strict"; var eval = 3.14; // This will cause an error
A string "arguments" cannot be used as a variable:
"use strict"; var arguments = 3.14; // Isso causará um erro
with
A instrução não é permitida:
"use strict"; with (Math){x = cos(2)}; // Isso causará um erro
Não é permitido eval()
Cria uma variável dentro do escopo onde ela foi chamada:
"use strict"; eval ("var x = 2"); alert (x); // Isso causará um erro
No chamado de função semelhante a f(), o valor de this é o objeto global. No modo estrito, agora ele se tornou undefined
.
Garantia para o futuro
Palavras-chave reservadas para o futuro não são permitidas no modo estrito. Elas são:
- implements
- interface
- let
- package
- private
- protected
- public
- static
- yield
"use strict"; var public = 1500; // Isso causará um erro
Aviso
"use strict"
Instruções podem apenas estar emInícioIdentificado.
- Página Anterior Hoisting JS
- Próxima Página Palavra-chave this JS