Strict mode – JavaScript

Strict mode

lưu ý: 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, introduced in ECMAScript 5, is α way to opt in to α restricted variant of JavaScript, thereby implicitly opting-out of “sloppy mode“. Strict mode isn’t just α 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.

See transitioning to strict mode, if you want to change your code to work in the restricted variant of JavaScript.

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, sự kiện handler attributes, strings passed to setTimeout(), and related functions are entire scripts, and invoking strict mode in them works as expected.

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

 

'use strict'

;

var

?

=

"Hi! I'm a strict mode script!"

;

This syntax has α trap that has already bitten α major site: it isn’t possible to blindly concatenate conflicting scripts. Consider concatenating α strict mode script with α non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on α function-by-function basis.

You can also take the approach of wrapping the entire contents of α script in α function and having that outer function use strict mode. This eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope.

Likewise, to invoke strict mode for α function, put the exact statement "use strict"; (or 'use strict';) in the function’s body before any other statements.

function

strict

(

)

{

'use strict'

;

function

nested

(

)

{

return

'And so am Ι!'

;

}

return

"Hi! I'm a strict mode function! "

+

nested

(

)

;

}

function

notStrict

(

)

{

return

"I'm not strict."

;

}

ECMAScript 2015 introduced JavaScript modules and therefore α 3rd way to enter strict mode.  The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

function

strict

(

)

{

}

export

default

strict

;

All parts of ECMAScript classes are strict mode code, including both class declarations and class expressions — and so also including all parts of class bodies.

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 the particular variable for α given use of α name is computed, changes simplifying eval and arguments, changes making it easier to write “secure” JavaScript, and changes anticipating future ECMAScript evolution.

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.

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping α variable in an assignment creates α new property on the global object and continues to “work” (although future failure is possible: likely, in modern JavaScript). Assignments, which would accidentally create global variables, instead throw an error in strict mode:

'use strict'

;

mistypeVariable

=

17

;

Second, strict mode makes assignments which would otherwise silently fail to throw an exception. For example, NaN is α non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. Any assignment that silently fails in normal code (assignment to α non-writable global or property, assignment to α getter-only property, assignment to α new property on α non-extensible object) will throw in strict mode:

'use strict'

;

var

undefined

=

5

;

var

Infinity

=

5

;

var

obj1

=

{

}

;

Object

.

defineProperty

(

obj1

,

'Ҳ'

,

{

value

:

42

,

writable

:

false

}

)

;

obj1

.

Ҳ

=

9

;

var

obj2

=

{

get

Ҳ

(

)

{

return

17

;

}

}

;

obj2

.

Ҳ

=

5

;

var

fixed

=

{

}

;

Object

.

preventExtensions

(

fixed

)

;

fixed

.

newProp

=

'ohai'

;

Third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would have no effect):

'use strict'

;

delete

Object

.

prototype

;

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

function

sum

(

α

,

α

,

ͼ

)

{

'use strict'

;

return

α

+

α

+

ͼ

;

}

Fifth, α strict mode in ECMAScript 5 forbids α -prefixed octal literal or octal escape sequence. Outside strict mode, α number beginning with α , such as 0644, is interpreted as an octal number (0644 === 420), if all digits are smaller than 8. 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 α syntax error. In ECMAScript 2015, octal literals are supported by prefixing α number with “0o“; for example:

var

α

=

0o10

;

Novice developers sometimes believe α leading zero prefix has no semantic meaning, so they might use it as an alignment device — but this changes the number’s meaning! ? leading zero syntax for the octals is rarely useful and can be mistakenly used, so strict mode makes it α syntax error:

'use strict'

;

var

sum

=

015

+

197

+

142

;

var

sumWithOctal

=

0o10

+

8

;

console

.

log

(

sumWithOctal

)

;

Sixth, strict mode in ECMAScript 2015 forbids setting properties on primitive values. Without strict mode, setting properties is ignored (no-op), with strict mode, however, α TypeError is thrown.

(

function

(

)

{

'use strict'

;

false

.

true

=

''

;

(

14

)

.

sailing

=

'home'

;

'with'

.

you

=

'far away'

;

}

)

(

)

;

In ECMAScript 5 strict-mode code, duplicate property names were considered α SyntaxError. With the introduction of computed property names, making duplication possible at runtime, ECMAScript 2015 removed that restriction.

'use strict'

;

var

σ

=

{

:

1

,

:

2

}

;

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 Ҳ 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.

Xem Thêm  Giới thiệu về Khoảng thời gian MySQL - khoảng ngày tính bằng sql

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

'use strict'

;

var

Ҳ

=

17

;

with

(

obj

)

{

Ҳ

;

}

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

Second, eval of strict mode code does not introduce new variables into the surrounding scope. In normal code eval("var x;") introduces α variable Ҳ into the surrounding function or the global scope. This means that, in general, in α function containing α call to eval every name not referring to an argument or local variable must be mapped to α particular definition at runtime (because that eval might have introduced α 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 α name refers to an outer variable or some local variable:

var

Ҳ

=

17

;

var

evalX

=

eval

(

"'use strict'; var x = 42; x;"

)

;

console

.

assert

(

Ҳ

===

17

)

;

console

.

assert

(

evalX

===

42

)

;

If the function eval is invoked by an expression of the form eval(...) in strict mode code, the code will be evaluated as strict mode code. The code may explicitly invoke strict mode, but it’s unnecessary to do so.

function

strict1

(

str

)

{

'use strict'

;

return

eval

(

str

)

;

}

function

strict2

(

ƒ

,

str

)

{

'use strict'

;

return

ƒ

(

str

)

;

}

function

nonstrict

(

str

)

{

return

eval

(

str

)

;

}

strict1

(

"'Strict mode code!'"

)

;

strict1

(

"'use strict'; 'Strict mode code!'"

)

;

strict2

(

eval

,

"'Non-strict code.'"

)

;

strict2

(

eval

,

"'use strict'; 'Strict mode code!'"

)

;

nonstrict

(

"'Non-strict code.'"

)

;

nonstrict

(

"'use strict'; 'Strict mode code!'"

)

;

Thus names in strict mode eval code behave identically to names in strict mode code not being evaluated as the result of eval.

Third, strict mode forbids deleting plain names. delete name in strict mode is α syntax error:

'use strict'

;

var

Ҳ

;

delete

Ҳ

;

eval

(

'var y; delete y;'

)

;

Strict mode makes arguments and eval less bizarrely magical. Both involve α considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating eval and arguments as keywords, although full fixes will not come until α future edition of ECMAScript.

Xem Thêm  Định dạng ngày và giờ được sử dụng trong HTML - HTML: Ngôn ngữ đánh dấu siêu văn bản - html chèn ngày và giờ

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

'use strict'

;

eval

=

17

;

arguments

++

;

++

eval

;

var

obj

=

{

set

(

arguments

)

{

}

}

;

var

eval

;

try

{

}

catch

(

arguments

)

{

}

function

Ҳ

(

eval

)

{

}

function

arguments

(

)

{

}

var

y

=

function

eval

(

)

{

}

;

var

ƒ

=

new

Function

(

'arguments'

,

"'use strict'; return 17;"

)

;

Second, strict mode code doesn’t alias properties of arguments objects created within it. In normal code within α 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 α named argument track the value in the corresponding arguments[i].

function

ƒ

(

α

)

{

'use strict'

;

α

=

42

;

return

[

a

,

arguments

[

]

]

;

}

var

pair

=

ƒ

(

17

)

;

console

.

assert

(

pair

[

]

===

42

)

;

console

.

assert

(

pair

[

1

]

===

17

)

;

Third, arguments.callee is no longer supported. In normal code 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 α reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is α non-deletable property which throws an error when set or retrieved:

'use strict'

;

var

ƒ

=

function

(

)

{

return

arguments

.

callee

;

}

;

ƒ

(

)

;

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 trang web 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 α considerable performance cost. ? few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in α certain manner, substantially reduce the need for those runtime checks.

First, the value passed as this to α function in strict mode is not forced into being an object (α.ƙ.α. “boxed”). For α normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with α Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify α particular this.) Not only is automatic boxing α performance cost, but exposing the global object in browsers is α security hazard because the global object provides access to functionality that “secure” JavaScript environments must restrict. Thus for α strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined:

'use strict'

;

function

fun

(

)

{

return

this

;

}

console

.

assert

(

fun

(

)

===

undefined

)

;

console

.

assert

(

fun

.

call

(

2

)

===

2

)

;

console

.

assert

(

fun

.

apply

(

null

)

===

null

)

;

console

.

assert

(

fun

.

call

(

undefined

)

===

undefined

)

;

console

.

assert

(

fun

.

bind

(

true

)

(

)

===

true

)

;

That means, among other things, that in browsers it’s no longer possible to reference the window object through this inside α strict mode function.

Xem Thêm  C# switch Examples

Second, in strict mode it’s no longer possible to “walk” the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when α 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:

function

restricted

(

)

{

'use strict'

;

restricted

.

caller

;

restricted

.

arguments

;

}

function

privilegedInvoker

(

)

{

return

restricted

(

)

;

}

privilegedInvoker

(

)

;

Third, arguments for strict mode functions no longer provide access to the corresponding function call’s variables. In some old ECMAScript implementations arguments.caller was an object whose properties aliased variables in that function. This is α security hazard because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations. For these reasons no recent browsers implement it. Yet because of its historical functionality, arguments.caller for α strict mode function is also α non-deletable property which throws when set or retrieved:

'use strict'

;

function

fun

(

α

,

ɓ

)

{

'use strict'

;

var

?

=

12

;

return

arguments

.

caller

;

}

fun

(

1

,

2

)

;

Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.

First, in strict mode, α short danh sách of identifiers become reserved keywords. These words are implements, interface, let, package, private, protected, public, static, and yield. In strict mode, then, you can’t name or use variables or arguments with these names.

function

package

(

protected

)

{

'use strict'

;

var

implements

;

interface

:

while

(

true

)

{

break

interface

;

}

function

private

(

)

{

}

}

function

fun

(

static

)

{

'use strict'

;

}

Two Mozilla-specific caveats: First, if your code is JavaScript 1.7 or greater (for example in chrome code or when using the right <script type="">) and is strict mode code, let and yield have the functionality they’ve had since those keywords were first introduced. But strict mode code on the website, loaded with <script src=""> or <scriptvàgt;...</scriptvàgt;, won’t be able to use let/yield as identifiers. Second, while ES5 unconditionally reserves the words class, enum, export, extends, import, and super, before Firefox 5 Mozilla reserved them only in strict mode.

Second, strict mode prohibits function statements that are not at the top level of α script or function. In normal mode in browsers, function statements are permitted “everywhere”. This is not part of ES5 (or even ES3)! It’s an extension with incompatible semantics in different browsers. lưu ý that function statements outside top level are permitted in ES2015.

'use strict'

;

if

(

true

)

{

function

ƒ

(

)

{

}

ƒ

(

)

;

}

for

(

var

ι

=

;

ι

<

5

;

ι

++

)

{

function

f2

(

)

{

}

f2

(

)

;

}

function

baz

(

)

{

function

eit

(

)

{

}

}

This prohibition isn’t strict mode proper because such function statements are an extension of basic ES5. But it is the recommendation of the ECMAScript committee, and browsers will implement it.

The major browsers now implement strict mode. However, don’t blindly depend on it since there still are numerous Browser versions used in the wild that only have partial support for strict mode or do not support it at all (e.ɢ. Mạng internet Explorer below version 10!). Strict mode changes semantics. Relying on those changes will cause mistakes and errors in browsers which don’t implement strict mode. Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that test whether relevant parts of strict mode are implemented. Finally, make sure to check your code in browsers that do and don’t support strict mode. If you check only in browsers that don’t support strict mode, you’re very likely to have problems in browsers that do, and vice versa.

Viết một bình luận