seunghyun Note

20장(strict mode) 본문

스터디/모던자바스크립트 deep dive

20장(strict mode)

승숭슝현 2024. 1. 8. 10:32

1. Strict mode란

자바스크립트 언어의 문법을 좀 더 엄격히 적용하여 오류를 발생시킬 가능성이 높거나 자바스크립트 엔진의 최적화 작업에 문제를 일으킬 수 있는 코드에 대한 명시적인 에러를 발생시킨다.

function foo() {
  x = 10;
}
foo();

console.log(x); // ?

위 예제를 실행하면 결과는 10이 출력된다.
x = 10 코드를 만나면 자바스크립트 엔진은 foo함수 스코프에서 x식별자를 검색한다.
foo함수 스코프에 없으면 스코프 체인을 통해 상위 스코프에서 x 변수를 검색한다. 즉, 전역 스코프에서 검색하는데, 전역 스코프에 없으면 RefferenceError가 발생해야 하는데 자바스크립트 엔진은 암묵적으로 전역 객체에 x프로퍼티를 동적으로 생성한다. 이를 암묵적 전역implicit global이라 한다.

이런 현상은 개발자의 의도와 다르게 동작할 우려가 있어 좋지 않다.
따라서 반드시 var, let, const키워드를 사용하여 변수를 선언한 다음 사용해야 한다. (키워드만 적어줘도 암묵적 전역은 발생하지 않는다.)

2. Strict mode의 적용

strict mode를 적용하려면 전역의 선두 또는 함수 몸체의 선두에 'use strict';를 추가한다. 전역의 선두에 추가하면 스크립트 전체에 strict mode가 적용된다.

전역

'use strict';

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

함수 안

function foo() {
  'use strict';

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

3.전역에 strict mode를 적용하는 것은 피하자

전역에 적용한 strict mode는 스크립트 단위로 적용된다.

<!DOCTYPE html>
<html>
<body>
  <script>
    'use strict';
  </script>
  <script>
    x = 1; // 에러가 발생하지 않는다.
    console.log(x); // 1
  </script>
  <script>
    'use strict';

    y = 1; // ReferenceError: y is not defined
    console.log(y);
  </script>
</body>
</html>

4.함수 단위로 strict mode를 적용하는 것도 피하자

함수 단위로 strict mode를 적용하게되면 모든 함수마다 일일이 strict mode를 적용해야 하는데 이는 매우 번거로운 일이다.

그리고 strict mode가 적용된 함수가 참조할 함수 외부의 컨텍스트에 strict mode를 적용하지 않는다면 문제가 발생할 수 있다.

(function () {
  // non-strict mode
  var lеt = 10; // 에러가 발생하지 않는다.

  function foo() {
    'use strict';

    let = 20; // SyntaxError: Unexpected strict mode reserved word
  }
  foo();
}());

5.strict mode가 발생시키는 에러

strict mode를 적용시켰을 때 발생하는 에러는 다음과 같다.

암묵적 전역

(function () {
  'use strict';

  x = 1;
  console.log(x); // ReferenceError: x is not defined
}());

변수, 함수, 매개변수의 삭제(delete)

(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.
}());

매개변수 이름의 중복

(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문의 사용

(function () {
  'use strict';

  // SyntaxError: Strict mode code may not include a with statement
  with({ x: 1 }) {
    console.log(x);
  }
}());

6.strict mode 적용에 의한 변화

strict mode에서 함수를 일반함수로 호출하면 this에 undefined가 바인딩된다.

생성자 함수가 아닌 일반 함수 내부에서는 this를 사용할 필요가 없기 때문이다.

(function () {
  'use strict';

  function foo() {
    console.log(this); // undefined
  }
  foo();

  function Foo() {
    console.log(this); // Foo
  }
  new Foo();
}());
728x90

'스터디 > 모던자바스크립트 deep dive' 카테고리의 다른 글

22장 (this)  (0) 2024.01.08
21장 (빌트인 객체)  (0) 2024.01.08
19장(프로토타입)  (1) 2024.01.08
18장(함수와 일급 객체)  (0) 2024.01.08
17장(생성자 함수에 의한 객체)  (1) 2024.01.08