20์ฅ strict mode
20.1 strict mode๋?
JS์ ๋ฌธ๋ฒ์ ์กฐ๊ธ ๋ ์๊ฒฉํ ์ ์ฉํ์ฌ ์ค๋ฅ๋ฅผ ๋ฐ์์ํฌ ๊ฐ๋ฅ์ฑ์ด ๋๊ฑฐ๋ ์ต์ ํ ์์ ์ ๋ฌธ์ ๋ฅผ ์ผ์ผํฌ ์ ์๋ ์ฝ๋์ ๋ํด ๋ช ์์ ์๋ฌ๋ฅผ ๋ฐ์์ํจ๋ค. (ESLint๋ ์ ์ฌํ ํจ๊ณผ๋ฅผ ์ป์ ์ ์์)
20.2 strict mode์ ์ ์ฉ
์ ์ญ์ ์ ๋ ๋๋ ํจ์ ๋ชธ์ฒด ์ ๋์ โuse strictโ;์ ์ถ๊ฐํ๋ค.
20.3 ์ ์ญ์ strict mode๋ฅผ ์ ์ฉํ๋ ๊ฒ์ ํผํ์
์ ์ญ์ ์ ์ฉํ strict mode๋ ์คํฌ๋ฆฝํธ ๋จ์๋ก ์ ์ฉ๋๋ค. strict mode ์คํฌ๋ฆฝํธ์ non-strict mode ์คํฌ๋ฆฝํธ๋ฅผ ํผ์ฉํ๋ ๊ฒ์ ์ค๋ฅ๋ฅผ ๋ฐ์์ํฌ ์ ์๋ค. ํนํ ์๋ํํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ non-strict mode์ธ ๊ฒฝ์ฐ๋ ์๊ธฐ์ ์ ์ญ์ strict mode๋ฅผ ์ ์ฉํ๋ ๊ฒ์ ๋ฐ๋์งํ์ง ์๋ค. ์ฆ์ ์คํ ํจ์๋ก ์คํฌ๋ฆฝํธ ์ ์ฒด๋ฅผ ๊ฐ์ธ์ ์ค์ฝํ๋ฅผ ๊ตฌ๋ถํ๊ณ ์ฆ์ ์คํ ํจ์์ ์ ๋์ strict mode๋ฅผ ์ ์ฉํ์.
20.4 ํจ์ ๋จ์๋ก strict mode๋ฅผ ์ ์ฉํ๋ ๊ฒ๋ ํผํ์
์คํฌ๋ฆฝํธ์ ๋ง์ฐฌ๊ฐ์ง๋ก strict mode ํจ์๋ฅผ ํผ์ฉํ๋ฉด ๋ฐ๋์งํ์ง ์๊ณ , ๋ชจ๋ ํจ์์ ์ ์ฉํ๊ธฐ๋ ๋ฒ๊ฑฐ๋กญ๋ค. ๊ทธ๋ฆฌ๊ณ ์ ์ฉ๋ ํจ์๊ฐ ์ฐธ์กฐํ ํจ์ ์ธ๋ถ์ ์ปจํ ์คํธ์ strict mode๋ฅผ ์ ์ฉํ์ง ์๋๋ค๋ฉด ์ด ๋ํ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ์ ์๋ค. ๋ฐ๋ผ์ strict mode๋ ์ฆ์ ์คํ ํจ์๋ก ๊ฐ์ผ ์คํฌ๋ฆฝํธ ๋จ์๋ก ์ ์ฉํ๋ ๊ฒ์ด ๋ฐ๋์งํ๋ค.
20.5 strict mode๊ฐ ๋ฐ์์ํค๋ ์๋ฌ
20.5.1
์ ์ธํ์ง ์์ ๋ณ์๋ฅผ ์ฐธ์กฐํ๋ฉด ReferenceError๊ฐ ๋ฐ์ํ๋ค.
(function(){
'use strict'
x = 1;
console.log(x) //ReferenceError: x is not defined
}())20.5.2 ๋ณ์, ํจ์, ๋งค๊ฐ๋ณ์์ ์ญ์
delete ์ฐ์ฐ์๋ก ๋ณ์, ํจ์, ๋งค๊ฐ๋ณ์๋ฅผ ์ญ์ ํ๋ฉด SyntaxError๊ฐ ๋ฐ์ํ๋ค.
(function(){
'use strict'
let x = 1
delete x // SyntaxError: Delete of an unqualified identifier in strict mode
function foo(a){
delete a // SyntaxError: Delete of an unqualified identifier in strict mode
}
delete foo // SyntaxError: Delete of an unqualified identifier in strict mode
}())20.5.3 ๋งค๊ฐ๋ณ์ ์ด๋ฆ์ ์ค๋ณต
์ค๋ณต๋ ๋งค๊ฐ๋ณ์ ์ด๋ฆ์ ์ฌ์ฉํ๋ฉด SyntaxError๊ฐ ๋ฐ์ํ๋ค.
(Function(){
'use strict'
// SyntaxError: Duplicate parameter name not allowed in this context
function foo(x, x){
return x + x;
}
console.log(foo(1,2))
}())20.5.4 with ๋ฌธ์ ์ฌ์ฉ
with ๋ฌธ์ ์ฌ์ฉํ๋ฉด SyntaxError๊ฐ ๋ฐ์ํ๋ค.
with ๋ฌธ์ ์ ๋ฌ๋ ๊ฐ์ฒด๋ฅผ ์ค์ฝํ ์ฒด์ธ์ ์ถ๊ฐํ๋ค. ๋์ผํ ๊ฐ์ฒด์ ํ๋กํผํฐ๋ฅผ ๋ฐ๋ณตํด์ ์ฌ์ฉํ ๋ ๊ฐ์ฒด ์ด๋ฆ์ ์๋ตํ ์ ์์ด์ ์ฝ๋๊ฐ ๊ฐ๋จํด์ง๋ ํจ๊ณผ๊ฐ ์์ง๋ง ์ฑ๋ฅ๊ณผ ๊ฐ๋ ์ฑ์ด ๋๋น ์ง๋ ๋ฌธ์ ๊ฐ ์๋ค. ๋ฐ๋ผ์ with ๋ฌธ์ ์ฌ์ฉํ์ง ์๋ ๊ฒ์ด ์ข๋ค.
(function(){
'use strict'
// SyntaxError: Strict mode code may not include a with statement
with({x:1}){
console.log(x)
}
}())20.6 strict mode ์ ์ฉ์ ์ํ ๋ณํ
20.6.1 ์ผ๋ฐ ํจ์์ this
strict mode ์์ ํจ์๋ฅผ ์ผ๋ฐ ํจ์๋ก์ ํธ์ถํ๋ฉด this์ undefined๊ฐ ๋ฐ์ธ๋ฉ๋๋ค. ์์ฑ์ ํจ์๊ฐ ์๋ ์ผ๋ฐ ํจ์ ๋ด๋ถ์์๋ this๋ฅผ ์ฌ์ฉํ ํ์๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ค. ์ด๋ ์๋ฌ๋ ๋ฐ์ํ์ง ์๋๋ค.
(function(){
'use strict'
function foo(){
console.log(this) // undefined
}
foo()
function Foo(){
console.log(this) // Foo
}
new Foo()
}())20.6.2 arguments ๊ฐ์ฒด
strict mode ์์๋ ๋งค๊ฐ๋ณ์์ ์ ๋ฌ๋ ์ธ์๋ฅผ ์ฌํ ๋นํ์ฌ ๋ณ๊ฒฝํด๋ arguments ๊ฐ์ฒด์ ๋ฐ์๋์ง ์๋๋ค.
(function(a){
'use strict'
// ๋งค๊ฐ๋ณ์์ ์ ๋ฌ๋ ์ธ์๋ฅผ ์ฌํ ๋นํ์ฌ ๋ณ๊ฒฝ
a = 2;
// ๋ณ๊ฒฝ๋ ์ธ์๊ฐ arguments ๊ฐ์ฒด์ ๋ฐ์๋์ง ์๋๋ค.
console.log(arguments) // { 0: 1, length: 1}
}(1))Last updated
Was this helpful?