๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Dive ๋์์ 20์ฅ์ ์ ๋ฆฌํ์์ต๋๋ค.
// 20-01
function foo() {
x = 10;
}
foo();
console.log(x); // ? ReferenceError๊ฐ ์๋ ์๋ฌต์ ์ผ๋ก ์ ์ญ ๊ฐ์ฒด์ x ํ๋กํผํฐ๋ฅผ ๋์ ์์ฑํจ => ์๋ฌต์ ์ ์ญ : ๋ฐ๋ผ์ 10 ์ถ๋ ฅ
์ ์ฌ์ ์ธ ์ค๋ฅ๋ฅผ ๋ฐ์์ํค๊ธฐ ์ด๋ ค์ด ๊ฐ๋ฐ ํ๊ฒฝ์ ๋ง๋ค๊ณ ๊ทธ ํ๊ฒฝ์์ ๊ฐ๋ฐํ๋ ๊ฒ์ด ์ข ๋ ๊ทผ๋ณธ์ ์ธ ํด๊ฒฐ์ฑ
์ด๋ผ๊ณ ํ ์ ์๋ค. ์ด๋ฅผ ์ง์ํ๊ธฐ ์ํด ES5๋ถํฐ strict mode(์๊ฒฉ ๋ชจ๋)
๊ฐ ์ถ๊ฐ๋์๋ค.
strict mode
๋ ์๋ฐ์คํฌ๋ฆฝํธ ์ธ์ด์ ๋ฌธ๋ฒ์ ์ข ๋ ์๊ฒฉํ ์ ์ฉํ์ฌ ์ค๋ฅ๋ฅผ ๋ฐ์์ํฌ ๊ฐ๋ฅ์ฑ์ด ๋๊ฑฐ๋ ์๋ฐ์คํฌ๋ฆฝํธ ์์ง์ ์ต์ ํ ์์
์ ๋ฌธ์ ๋ฅผ ์ผ์ผํฌ ์ ์๋ ์ฝ๋์ ๋ํด ๋ช
์์ ์๋ฌ๋ฅผ ๋ฐ์์ํจ๋ค.
์ ์ญ์ ์ ๋ ํน์ ํจ์ ๋ชธ์ฒด์ ์ ๋์ use strict
๋ฅผ ์ถ๊ฐํ๋ค. ๊ทธ๋ฌ๋ฉด ์คํฌ๋ฆฝํธ ์ ์ฒด์ ์๊ฒฉ ๋ชจ๋๊ฐ ์ ์ฉ๋๋ค.
// 20-04
function foo() {
x = 10; // ์๋ฌ๋ฅผ ๋ฐ์์ํค์ง ์๋๋ค.
'use strict';
}
foo();
์ ์ธํ์ง ์์ ๋ณ์๋ฅผ ์ฐธ์กฐํ๋ฉด ReferenceError๊ฐ ๋ฐ์ํ๋ค.
(function() {
'use strict';
x = 1;
console.log(x); // ReferenceError: x is not defined
}());
delete ์ฐ์ฐ์๋ก ๋ณ์, ํจ์, ๋งค๊ฐ๋ณ์๋ฅผ ์ญ์ ํ๋ฉด SyntaxError๊ฐ ๋ฐ์ํ๋ค.
(function() {
'use strict';
var 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
}());
์ค๋ณต๋ ๋งค๊ฐ๋ณ์ ์ด๋ฆ์ ์ฌ์ฉํ๋ฉด 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));
}());
with๋ฌธ์ ์ฌ์ฉํ๋ฉด SyntaxError๊ฐ ๋ฐ์ํ๋ค.
(function() {
'use strict'; // SyntaxError: Strict mode code may not include a with Statement
with({ x : 1 }) {
console.log(x);
}
}());
strict mode์์ ํจ์๋ฅผ ์ผ๋ฐ ํจ์๋ก์ ํธ์ถํ๋ฉด this์ undefined๊ฐ ๋ฐ์ธ๋ฉ๋๋ค.
(function() {
'use strict';
function foo() {
console.log(this); // undefined
}
foo();
function Foo() {
console.log(this); // Foo
}
new Foo();
}());
strict mode์์๋ ๋งค๊ฐ๋ณ์์ ์ ๋ฌ๋ ์ธ์๋ฅผ ์ฌํ ๋นํ์ฌ ๋ณ๊ฒฝํด๋ arguments ๊ฐ์ฒด์ ๋ฐ์๋์ง ์๋๋ค.
(function(a) {
'use strict';
// ๋งค๊ฐ๋ณ์์ ์ ๋ฌ๋ ์ธ์๋ฅผ ์ฌํ ๋นํ์ฌ ๋ณ๊ฒฝ
a = 2;
// ๋ณ๊ฒฝ๋ ์ธ์๊ฐ arguments ๊ฐ์ฒด์ ๋ฐ์๋์ง ์๋๋ค.
console.log(arguments); // { 0: 1, length: 1 }
}(1));
Ref
- ์ด์ ๋ชจ ์ , โ๋ชจ๋ ์๋ฐ์คํฌ๋ฆฝํธ Deep Diveโ, ์ํค๋ถ์ค