What is use strict in javascript

Строгий режим — «use strict»

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

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

Так было до 2009 года, когда появился ECMAScript 5 (ES5). Он добавил новые возможности в язык и изменил некоторые из существующих. Чтобы устаревший код работал, как и раньше, по умолчанию подобные изменения не применяются. Поэтому нам нужно явно их активировать с помощью специальной директивы: «use strict» .

«use strict»

Директива выглядит как строка: «use strict» или ‘use strict’ . Когда она находится в начале скрипта, весь сценарий работает в «современном» режиме.

"use strict"; // этот код работает в современном режиме . 

Позже мы изучим функции (способ группировки команд). Забегая вперёд, заметим, что вместо всего скрипта «use strict» можно поставить в начале большинства видов функций. Это позволяет включить строгий режим только в конкретной функции. Но обычно люди используют его для всего файла.

Проверьте, что «use strict» находится в первой исполняемой строке скрипта, иначе строгий режим может не включиться.

Здесь строгий режим не включён:

alert("some code"); // "use strict" ниже игнорируется - он должен быть в первой строке "use strict"; // строгий режим не активирован

Над «use strict» могут быть записаны только комментарии.

Читайте также:  Java to kotlin translate

Нет директивы типа «no use strict» , которая возвращала бы движок к старому поведению.

Как только мы входим в строгий режим, отменить это невозможно.

Консоль браузера

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

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

Итак, как можно включить use strict в консоли?

Можно использовать Shift + Enter для ввода нескольких строк и написать в верхней строке use strict :

В большинстве браузеров, включая Chrome и Firefox, это работает.

Если этого не происходит, например, в старом браузере, есть некрасивый, но надежный способ обеспечить use strict . Поместите его в следующую обёртку:

Всегда ли нужно использовать «use strict»?

Вопрос кажется риторическим, но это не так.

Кто-то посоветует начинать каждый скрипт с «use strict» … Но есть способ покруче.

Современный JavaScript поддерживает «классы» и «модули» — продвинутые структуры языка (и мы, конечно, до них доберёмся), которые автоматически включают строгий режим. Поэтому в них нет нужды добавлять директиву «use strict» .

Подытожим: пока очень желательно добавлять «use strict»; в начале ваших скриптов. Позже, когда весь ваш код будет состоять из классов и модулей, директиву можно будет опускать.

Пока мы узнали о use strict только в общих чертах.

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

Все примеры в этом учебнике подразумевают исполнение в строгом режиме, за исключением случаев (очень редких), когда оговорено иное.

Источник

JavaScript Use Strict

«use strict»; Defines that JavaScript code should be executed in «strict mode».

The «use strict» Directive

The «use strict» directive was new in ECMAScript version 5.

It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

The purpose of «use strict» is to indicate that the code should be executed in «strict mode».

With strict mode, you can not, for example, use undeclared variables.

All modern browsers support «use strict» except Internet Explorer 9 and lower:

Directive
«use strict» 13.0 10.0 4.0 6.0 12.1

The numbers in the table specify the first browser version that fully supports the directive.

You can use strict mode in all your programs. It helps you to write cleaner code, like preventing you from using undeclared variables.

«use strict» is just a string, so IE 9 will not throw an error even if it does not understand it.

Declaring Strict Mode

Strict mode is declared by adding «use strict»; to the beginning of a script or a function.

Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode):

Example

Example

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

Declared inside a function, it has local scope (only the code inside the function is in strict mode):

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

function myFunction() «use strict»;
y = 3.14; // This will cause an error
>

The «use strict»; Syntax

The syntax, for declaring strict mode, was designed to be compatible with older versions of JavaScript.

Compiling a numeric literal (4 + 5;) or a string literal («John Doe»;) in a JavaScript program has no side effects. It simply compiles to a non existing variable and dies.

So «use strict»; only matters to new compilers that «understand» the meaning of it.

Why Strict Mode?

Strict mode makes it easier to write «secure» JavaScript.

Strict mode changes previously accepted «bad syntax» into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.

In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Not Allowed in Strict Mode

Using a variable, without declaring it, is not allowed:

Objects are variables too.

Using an object, without declaring it, is not allowed:

«use strict»;
x = ; // This will cause an error

Deleting a variable (or object) is not allowed.

Deleting a function is not allowed.

Duplicating a parameter name is not allowed:

Octal numeric literals are not allowed:

Octal escape characters are not allowed:

Writing to a read-only property is not allowed:

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

Writing to a get-only property is not allowed:

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

Deleting an undeletable property is not allowed:

The word eval cannot be used as a variable:

The word arguments cannot be used as a variable:

The with statement is not allowed:

For security reasons, eval() is not allowed to create variables in the scope from which it was called.

In strict mode, a variable can not be used before it is declared:

In strict mode, eval() can not declare a variable using the var keyword:

eval() can not declare a variable using the let keyword:

The this keyword in functions behaves differently in strict mode.

The this keyword refers to the object that called the function.

If the object is not specified, functions in strict mode will return undefined and functions in normal mode will return the global object (window):

Future Proof!

Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode.

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield

Watch Out!

The «use strict» directive is only recognized at the beginning of a script or a function.

Источник

Оцените статью