Js use strict что это

от admin

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:

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.

The modern mode, "use strict"

For a long time, JavaScript evolved without compatibility issues. New features were added to the language while old functionality didn’t change.

That had the benefit of never breaking existing code. But the downside was that any mistake or an imperfect decision made by JavaScript’s creators got stuck in the language forever.

This was the case until 2009 when ECMAScript 5 (ES5) appeared. It added new features to the language and modified some of the existing ones. To keep the old code working, most such modifications are off by default. You need to explicitly enable them with a special directive: "use strict" .

“use strict”

The directive looks like a string: "use strict" or ‘use strict’ . When it is located at the top of a script, the whole script works the “modern” way.

Quite soon we’re going to learn functions (a way to group commands), so let’s note in advance that "use strict" can be put at the beginning of a function. Doing that enables strict mode in that function only. But usually people use it for the whole script.

Please make sure that "use strict" is at the top of your scripts, otherwise strict mode may not be enabled.

Strict mode isn’t enabled here:

Only comments may appear above "use strict" .

There is no directive like "no use strict" that reverts the engine to old behavior.

Once we enter strict mode, there’s no going back.

Browser console

When you use a developer console to run code, please note that it doesn’t use strict by default.

Sometimes, when use strict makes a difference, you’ll get incorrect results.

So, how to actually use strict in the console?

First, you can try to press Shift + Enter to input multiple lines, and put use strict on top, like this:

It works in most browsers, namely Firefox and Chrome.

If it doesn’t, e.g. in an old browser, there’s an ugly, but reliable way to ensure use strict . Put it inside this kind of wrapper:

Should we “use strict”?

The question may sound obvious, but it’s not so.

One could recommend to start scripts with "use strict" … But you know what’s cool?

Modern JavaScript supports “classes” and “modules” – advanced language structures (we’ll surely get to them), that enable use strict automatically. So we don’t need to add the "use strict" directive, if we use them.

So, for now "use strict"; is a welcome guest at the top of your scripts. Later, when your code is all in classes and modules, you may omit it.

As of now, we’ve got to know about use strict in general.

In the next chapters, as we learn language features, we’ll see the differences between the strict and old modes. Luckily, there aren’t many and they actually make our lives better.

All examples in this tutorial assume strict mode unless (very rarely) specified otherwise.

Что значит "use strict"?

Нередко встречается код со строкой «use strict»; . Например, библиотеки часто начинаются с этого:

Что значит «use strict» , и зачем его использовать?

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

Строгий режим был введён в ECMAScript 5, и старые браузеры (IE9 и младше) его не поддерживают. То есть, не обращают внимания на установку по умолчанию и всё обрабатывается в неограниченном режиме.

Зачем использовать «use strict»; ?

В строгом режиме:

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

Как использовать «use strict»; ?

Чтобы включить строгий режим в целом скрипте, надо поставить установку «use strict»; или ‘use strict’; в начало скрипта.

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

В чём различие между строгим режимом и неограниченным режимом?

В строгом режиме:

нельзя присваивать значение в неопределённую переменную (спецификация §11.13.1). В неограниченном режиме создается глобальная переменная.

Также нельзя присваивать значение в свойство данных только для чтения.

нельзя использовать инструкцию with (спецификация §12.10).

в ES5 нельзя определить повторные свойства в литерале объекта (спецификация §11.1.5).

нельзя определить повторные формальные параметры функции (спецификация §13.1, §15.3.2).

изменения объекта arguments не изменяют аргументы (спецификация §10.6).

delete приводит к ошибке, если аргумент — не изменяемое свойство объекта (спецификация §11.4.1).

eval не может инстанциировать переменные и функции в контексте вызова (спецификация §10.4.2).

this не преобразуется в объект, а если значение this — undefined или null , то не преобразуется в глобальный объект (спецификация §10.4.3).

eval и arguments — нельзя изменить или использовать в качестве имени (спецификация §11.4.4, §11.4.5, §11.13, §12.2.1, §12.10, §12.14.1, §13.1).

нельзя использовать argument.caller и arguments.callee (спецификация §13.2).

больше слов, зарезервированных для использования в будущем (спецификация §7.6.1.2).

нельзя использовать литералы восьмеричной СС (спецификация B.1.1, B.1.2).

Name already in use

content / files / en-us / web / javascript / reference / strict_mode / index.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Note: Sometimes you’ll see the default, non-strict mode referred to as sloppy mode. This isn’t an official term, but be aware of it, just in case.

JavaScript’s strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of «sloppy mode». Strict mode isn’t just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don’t rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

Strict mode makes several changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
  3. Prohibits some syntax likely to be defined in future versions of ECMAScript.

Invoking strict mode

Strict mode applies to entire scripts or to individual functions. It doesn’t apply to block statements enclosed in <> braces; attempting to apply it to such contexts does nothing. eval code, Function code, event handler attributes, strings passed to setTimeout() , and related functions are either function bodies or entire scripts, and invoking strict mode in them works as expected.

Strict mode for scripts

To invoke strict mode for an entire script, put the exact statement «use strict»; (or ‘use strict’; ) before any other statements.

Strict mode for functions

Likewise, to invoke strict mode for a function, put the exact statement «use strict»; (or ‘use strict’; ) in the function’s body before any other statements.

The «use strict» directive can only be applied to the body of functions with simple parameters. Using «use strict» in functions with rest, default, or destructured parameters is a syntax error.

Strict mode for modules

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

Strict mode for classes

All parts of a class’s body are strict mode code, including both class declarations and class expressions.

Changes in strict mode

Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories:

  • changes converting mistakes into errors (as syntax errors or at runtime)
  • changes simplifying how variable references are resolved
  • changes simplifying eval and arguments
  • changes making it easier to write «secure» JavaScript
  • changes anticipating future ECMAScript evolution.

Converting mistakes into errors

Strict mode changes some previously-accepted mistakes into errors. JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics. Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. Strict mode treats these mistakes as errors so that they’re discovered and promptly fixed.

Assigning to undeclared variables

Strict mode makes it impossible to accidentally create global variables. In sloppy mode, mistyping a variable in an assignment creates a new property on the global object and continues to «work». Assignments which would accidentally create global variables throw an error in strict mode:

Failing to assign to object properties

Strict mode makes assignments which would otherwise silently fail to throw an exception. There are three ways to fail a property assignment:

  • assignment to a non-writable data property
  • assignment to a getter-only accessor property
  • assignment to a new property on a non-extensible object

For example, NaN is a non-writable global variable. In sloppy mode, assigning to NaN does nothing; the developer receives no failure feedback. In strict mode, assigning to NaN throws an exception.

Failing to delete object properties

Attempts to delete a non-configurable or otherwise undeletable (e.g. it’s intercepted by a proxy’s deleteProperty handler which returns false ) property throw in strict mode (where before the attempt would have no effect):

Strict mode also forbids deleting plain names. delete name in strict mode is a syntax error:

If the name is a configurable global property, prefix it with globalThis to delete it.

Duplicate parameter names

Strict mode requires that function parameter names be unique. In sloppy mode, the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments , so they’re not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode, duplicate argument names are a syntax error:

Legacy octal literals

Strict mode forbids a 0 -prefixed octal literal or octal escape sequence. In sloppy mode, a number beginning with a 0 , such as 0644 , is interpreted as an octal number ( 0644 === 420 ), if all digits are smaller than 8. Novice developers sometimes believe a leading-zero prefix has no semantic meaning, so they might use it as an alignment device — but this changes the number’s meaning! A leading-zero syntax for the octal is rarely useful and can be mistakenly used, so strict mode makes it a syntax error:

The standardized way to denote octal literals is via the 0o prefix. For example:

Octal escape sequences, such as «\45» , which is equal to «%» , can be used to represent characters by extended-ASCII character code numbers in octal. In strict mode, this is a syntax error. More formally, it’s disallowed to have \ followed by any decimal digit other than 0 , or \0 followed by a decimal digit; for example \9 and \07 .

Setting properties on primitive values

Strict mode forbids setting properties on primitive values. Accessing a property on a primitive implicitly creates a wrapper object that’s unobservable, so in sloppy mode, setting properties is ignored (no-op). In strict mode, a <> is thrown.

Duplicate property names

Duplicate property names used to be considered a <> in strict mode. With the introduction of computed property names, making duplication possible at runtime, this restriction was removed in ES2015.

Note: Making code that used to error become non-errors is always considered backwards-compatible. This is a good part of the language being strict about throwing errors: it leaves room for future semantic changes.

Simplifying scope management

Strict mode simplifies how variable names map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that variable X is stored in that location: this is critical to fully optimizing JavaScript code. JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform until runtime. Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.

Removal of the with statement

Strict mode prohibits with . The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at runtime; it’s impossible to know which beforehand. Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at runtime:

The simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace with .

In strict mode, eval does not introduce new variables into the surrounding scope. In sloppy mode, eval(«var x;») introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval , every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode, eval creates variables only for the code being evaluated, so eval can’t affect whether a name refers to an outer variable or some local variable:

Whether the string passed to eval() is evaluated in strict mode depends on how eval() is invoked (direct eval or indirect eval).

Block-scoped function declarations

The JavaScript language specification, since its start, had not allowed function declarations nested in block statements. However, it was so intuitive that most browsers implemented it as an extension grammar. Unfortunately, the implementations’ semantics diverged, and it became impossible for the language specification to reconcile all implementations. Therefore, block-scoped function declarations are only explicitly specified in strict mode (whereas they were once disallowed in strict mode), while sloppy mode behavior remains divergent among browsers.

Making eval and arguments simpler

Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in sloppy mode: eval to add or remove bindings and to change binding values, and arguments syncing named arguments with its indexed properties. Strict mode makes great strides toward treating eval and arguments as keywords.

Preventing binding or assigning eval and arguments

The names eval and arguments can’t be bound or assigned in language syntax. All these attempts to do so are syntax errors:

No syncing between parameters and arguments indices

Strict mode code doesn’t sync indices of the arguments object with each parameter binding. In a sloppy mode function whose first argument is arg , setting arg also sets arguments[0] , and vice versa (unless no arguments were provided or arguments[0] is deleted). arguments objects for strict mode functions store the original arguments when the function was invoked. arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i] .

Strict mode makes it easier to write «secure» JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript in browsers can access the user’s private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality. JavaScript’s flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has a considerable performance cost. A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.

No this substitution

The value passed as this to a function in strict mode is not forced into being an object (a.k.a. «boxed»). For a sloppy mode function, this is always an object: either the provided object, if called with an object-valued this ; or the boxed value of this , if called with a primitive as this ; or the global object, if called with undefined or null as this . (Use call , apply , or bind to specify a particular this .) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that «secure» JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this is undefined instead of globalThis :

Removal of stack-walking properties

In strict mode it’s no longer possible to «walk» the JavaScript stack. Many implementations used to implement some extension features that make it possible to detect the upstream caller of a function. When a function fun is in the middle of being called, fun.caller is the function that most recently called fun , and fun.arguments is the arguments for that invocation of fun . Both extensions are problematic for «secure» JavaScript because they allow «secured» code to access «privileged» functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw when set or retrieved:

Similarly, arguments.callee is no longer supported. In sloppy mode, arguments.callee refers to the enclosing function. This use case is weak: name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws an error when set or retrieved:

Extra reserved words

Reserved words are identifiers that can’t be used as variable names. Strict mode reserves some more names than sloppy mode, some of which are already used in the language, and some of which are reserved for the future to make future syntax extensions easier to implement.

  • implements
  • interface
  • package
  • private
  • protected
  • public

Transitioning to strict mode

Strict mode has been designed so that the transition to it can be made gradually. It is possible to change each file individually and even to transition code to strict mode down to the function granularity.

You can migrate a codebase to strict mode by first adding «use strict» to a piece of source code, and then fixing all execution errors, while watching out for semantic differences.

When adding ‘use strict’; , the following cases will throw a <> before the script is executing:

  • Octal syntax const n = 023; statement
  • Using delete on a variable name delete myVariable ;
  • Using eval or arguments as variable or function argument name
  • Using one of the newly reserved keywords (in prevision for future language features): implements , interface , let , package , private , protected , public , static , and yield
  • Declaring two function parameters with the same name function f(a, b, b) <>
  • Declaring the same property name twice in an object literal . This constraint was later removed (bug 1041128).

These errors are good, because they reveal plain errors or bad practices. They occur before the code is running, so they are easily discoverable as long as the code gets parsed by the runtime.

New runtime errors

JavaScript used to silently fail in contexts where what was done should be an error. Strict mode throws in such cases. If your code base contains such cases, testing will be necessary to be sure nothing is broken. You can screen for such errors at the function granularity level.

  • Assigning to an undeclared variable throws a <>. This used to set a property on the global object, which is rarely the expected effect. If you really want to set a value to the global object, explicitly assign it as a property on globalThis .
  • Failing to assign to an object’s property (e.g. it’s read-only) throws a <>. In sloppy mode, this would silently fail.
  • Deleting a non-deletable property throws a <>. In sloppy mode, this would silently fail.
  • Accessing arguments.callee , strictFunction.caller , or strictFunction.arguments throws a <> if the function is in strict mode. If you are using arguments.callee to call the function recursively, you can use a named function expression instead.

These differences are very subtle differences. It’s possible that a test suite doesn’t catch this kind of subtle difference. Careful review of your code base will probably be necessary to be sure these differences don’t affect the semantics of your code. Fortunately, this careful review can be done gradually down the function granularity.

Читать:
Сколько дм в одном сантиметре

Похожие статьи