LEARNING JAVASCRIPT - Trang 152

The

typeof

operator is commonly used to determine if a variable has been declared,

and is considered a “safe” way to test for existence. That is, prior to

let

and the TDZ,

for any identifier

x

, this was always a safe operation that would not result in an error:

if

(

typeof

x

===

"undefined"

) {

console

.

log

(

"x doesn't exist or is undefined"

);

}

else

{

// safe to refer to x....

}

This code is no longer safe with variables declared with

let

. The following will result

in an error:

if

(

typeof

x

===

"undefined"

) {

console

.

log

(

"x doesn't exist or is undefined"

);

}

else

{

// safe to refer to x....

}

let

x

=

5

;

Checking whether or not variables are defined with

typeof

will be less necessary in

ES6, so in practice, the behavior of

typeof

in the TDZ should not cause a problem.

Strict Mode

The syntax of ES5 allowed for something called implicit globals, which have been the

source of many frustrating programming errors. In short, if you forgot to declare a

variable with

var

, JavaScript would merrily assume you were referring to a global

variable. If no such global variable existed, it would create one! You can imagine the

problems this caused.
For this (and other) reasons, JavaScript introduced the concept of strict mode, which

would prevent implicit globals. Strict mode is enabled with the string

"use strict"

(you can use single or double quotes) on a line by itself, before any other code. If you

do this in global scope, the entire script will execute in strict mode, and if you do it in

a function, the function will execute in strict mode.
Because strict mode applies to the entire script if used in the global scope, you should

use it with caution. Many modern websites combine various scripts together, and

strict mode in the global scope of one will enable strict mode in all of them. While it

would be nice if all scripts worked correctly in strict mode, not all of them do. So it’s

generally inadvisable to use strict mode in global scope. If you don’t want to enable

strict mode in every single function you write (and who would?), you can wrap all of

your code in one function that’s executed immediately (something we’ll learn more

about in

Chapter 13

):

128 | Chapter 7: Scope

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.