๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
javascript/๐Ÿ“– study

[4์ฃผ์ฐจ ์Šคํ„ฐ๋””] 20์žฅ- strict mode

by HomieKim 2022. 2. 23.

strict mode

strict mode ๋ž€?

  • ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์–ธ์–ด์˜ ๋ฌธ๋ฒ•์„ ์ข€ ๋” ์—„๊ฒฉํžˆ ์ ์šฉํ•˜์—ฌ ์˜ค๋ฅ˜๋ฅผ ๋ฐœ์ƒ์‹œํ‚ฌ ๊ฐ€๋Šฅ์„ฑ์ด ๋†’๊ฑฐ๋‚˜ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์—”์ง„์˜ ์ตœ์ ํ™” ์ž‘์—…์— ๋ฌธ์ œ๋ฅผ ์ผ์œผํ‚ฌ ์ˆ˜ ์žˆ๋Š” ์ฝ”๋“œ์— ๋Œ€ํ•ด ๋ช…์‹œ์ ์ธ ์—๋Ÿฌ๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ๋‹ค.
  • ESLint ๊ฐ™์€ ๋ฆฐํŠธ ๋„๊ตฌ๋ฅผ ์‚ฌ์šฉํ•ด๋„ strict ๋ชจ๋“œ์™€ ์œ ์‚ฌํ•œ ํšจ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค.
  • ๋ฆฐํŠธ ๋„๊ตฌ๋ž€ ์ •์  ๋ถ„์„ ๊ธฐ๋Šฅ์„ ํ†ตํ•ด ์†Œ์Šค์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์ „์— ์†Œ์Šค์ฝ”๋“œ๋ฅผ ์Šค์บ”ํ•˜์—ฌ ๋ฌธ๋ฒ•์  ์˜ค๋ฅ˜ ๋งŒ์ด ์•„๋‹ˆ๋ผ ์ž ์žฌ์  ์˜ค๋ฅ˜๊นŒ์ง€ ์ฐพ์•„๋‚ด๊ณ  ์˜ค๋ฅ˜์˜ ์›์ธ์„ ๋ฆฌํฌํŒ…ํ•ด์ฃผ๋Š” ๋„๊ตฌ์ด๋‹ค.
  • ESLint์‚ฌ์šฉ๋ฐฉ๋ฒ•

strict mode ์˜ ์ ์šฉ

  • ์ „์—ญ์˜ ์„ ๋„ ๋˜๋Š” ํ•จ์ˆ˜ ๋ชธ์ฒด์˜ ์„ ๋‘์— 'use scritct'; ํ‚ค์›Œ๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ์‚ฌ์šฉ
  • ์ „์—ญ์— ์‚ฌ์šฉ์‹œ ์Šคํฌ๋ฆฝํŠธ ์ „์ฒด์— strict mode ์ ์šฉ
'use strict';

function foo() {
    x = 10; // ReferenceError : x is not defined
}
foo();

์ „์—ญ์— strict mode๋ฅผ ์ ์šฉํ•˜๋Š” ๊ฒƒ์€ ํ”ผํ•˜์ž

  • ์ „์—ญ์— ์ ์šฉํ•œ strict mode๋Š” ์Šคํฌ๋ฆฝํŠธ ๋‹จ์œ„๋กœ ์ ์šฉ๋จ
  • ๋‹ค๋ฅธ ์Šคํฌ๋ฆฝํŠธ์— ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— strict mode์™€ non strict-mode๋ฅผ ํ˜ผ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์ข‹์ง€ ์•Š์Œ
  • ์ฆ‰์‹œ ์‹คํ–‰ ํ•จ์ˆ˜๋กœ ๊ฐ์‹ธ์„œ ํ•ด๊ฒฐ ๊ฐ€๋Šฅ

strict mode๊ฐ€ ๋ฐœ์ƒ ์‹œํ‚ค๋Š” ์—๋Ÿฌ

์•”๋ฌต์  ์ „์—ญ

  • ์„ ์–ธํ•˜์ง€ ์•Š์€ ๋ณ€์ˆ˜๋ฅผ ์ฐธ์กฐํ•˜๋ฉด Reference Error
(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));
}());

๋Œ“๊ธ€