JavaScript «используйте строгий»


Оглавление

    Показать оглавление


"use strict"; Определяет это Код JavaScript должен выполняться в «строгий режим».


Директива «use strict»

Директива use strict была новой в ECMAScript версии 5.

Это не утверждение, а буквальное выражение, игнорируемое более ранними версиями. JavaScript.

Целью "use strict" является указание на то, что код должен выполняться в "строгом режиме".

В строгом режиме вы не сможете, например, использовать необъявленные переменные.

Все современные браузеры поддерживают использование строгого режима, кроме Internet Explorer 9 и более ранних версий:

Directive
"use strict" 13.0 10.0 4.0 6.0 12.1

Цифры в таблице указывают первую версию браузера, полностью поддерживающую директиву.

Вы можете использовать строгий режим во всех своих программах. Это поможет вам писать более чистый код, например, запретить вам использовать необъявленные переменные.

"use strict" — это просто строка, поэтому IE 9 не выдаст ошибку, даже если он ее не понимает.


Объявление строгого режима

Строгий режим объявляется добавлением "use strict"; в начало скрипт или функция.

Объявленный в начале скрипта, он имеет глобальную область действия (весь код в скрипте будет выполняться в строгом режиме):

Пример

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

Попробуйте сами →

<!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>

Пример

"use strict";
myFunction();

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

Попробуйте сами →

<!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>

Объявленный внутри функции, он имеет локальную область видимости (только код внутри функции в строгом режиме):

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

Попробуйте сами →

<!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>


«Использовать строго»; Синтаксис

Синтаксис объявления строгого режима был разработан для совместимости с старые версии JavaScript.

Компиляция числового литерала (4 + 5;) или строкового литерала («Джон Доу»;) в Программа JavaScript не имеет побочных эффектов. Он просто компилируется в несуществующий файл. переменная и умирает.

Таким образом, "use strict"; имеет значение только для новых компиляторов, которые "понимают" значение этого.


Почему строгий режим?

Строгий режим упрощает написание «безопасного» JavaScript.

Строгий режим заменяет ранее принятый «плохой синтаксис» реальными ошибками.

Например, в обычном JavaScript ошибочный ввод имени переменной приводит к созданию новой глобальная переменная. В строгом режиме это вызовет ошибку, что сделает невозможным случайно создать глобальную переменную.

В обычном JavaScript разработчик не получит никаких сообщений об ошибках. присвоение значений недоступным для записи свойствам.

В строгом режиме любое присвоение свойству, недоступному для записи, доступно только для получения. свойство, несуществующее свойство, несуществующая переменная или несуществующая объект, выдаст ошибку.


Не разрешено в строгом режиме

Использование переменной без ее объявления не допускается:

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

Попробуйте сами →

<!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>

Объекты тоже являются переменными.

Использование объекта без его объявления не допускается:

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

Попробуйте сами →

<!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>

Удаление переменной (или объекта) не допускается.

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

Попробуйте сами →

<!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>

Удаление функции не допускается.

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

Попробуйте сами →

<!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>

Дублирование имени параметра не допускается:

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

Попробуйте сами →

<!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>

Восьмеричные числовые литералы не допускаются:

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

Попробуйте сами →

<!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>

Восьмеричные escape-символы не допускаются:

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

Попробуйте сами →

<!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>

Запись в свойство, доступное только для чтения, не разрешена:

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

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

Попробуйте сами →

<!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>

Запись в свойство get-only не разрешена:

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

Попробуйте сами →

<!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>

Удаление неудаляемого свойства не допускается:

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

Попробуйте сами →

<!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>

Слово eval нельзя использовать в качестве переменной:

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

Попробуйте сами →

<!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>

Слово аргументы нельзя использовать в качестве переменной:

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

Попробуйте сами →

<!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>

Оператор with не допускается:

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

Попробуйте сами →

<!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>

По соображениям безопасности eval() не разрешено создавать переменные в области, из которой они были вызваны.

В строгом режиме переменную нельзя использовать до ее объявления:

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

Попробуйте сами →

<!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>

В строгом режиме eval() не может объявить переменную с помощью ключевого слова var:

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

Попробуйте сами →

<!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() не может объявить переменную с помощью ключевого слова let:

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

Попробуйте сами →

<!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>

Ключевое слово this в функциях ведет себя иначе в строгом режиме.

Ключевое слово this относится к объекту, который называется функцией.

Если объект не указан, работает в строгом режиме. вернет undefined и будет работать нормально mode вернет глобальный объект (окно):

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

Попробуйте сами →

<!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>

На будущее!

Ключевые слова, зарезервированные для будущих версий JavaScript, НЕ могут использоваться в качестве переменных. имена в строгом режиме.

Это:

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

Попробуйте сами →

<!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>

Осторожно!

Директива use strict распознается только в начале скрипта. или функция.