[모던 자바스크립트 Deep Dive] 20장. strict mode

윤상준·2022년 12월 19일
0
post-thumbnail

20.1 strict mode란?

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

console.log(x); // ?

전역 스코프에 x 변수 선언이 없어 ReferenceError가 발생할 것 같지만, 아무런 에러도 발생하지 않는다.

암묵적 전역 (Implicit Global)
자바스크립트 엔진은 암묵적으로 전역 객체에 x 프로퍼티를 동적 생성한다. 따라서 전역 변수처럼 사용할 수 있다.

암묵적 전역은 오류를 발생시킬 수 있기 때문에 반드시 var, let, const 키워드를 사용해야 한다.

strict mode (엄격 모드)

  • ES5 부터 추가된 모드.
  • 자바스크립트 언어의 문법을 더 엄격하게 적용하여 오류를 발생시킬 가능성이 높다.
  • 자바스크립트 엔진의 최적화 작업에 문제를 일으킬 수 있는 코드에 명시적인 에러를 발생시킬 수 있다.

20.2 strict mode의 적용

전역 또는 함수 몸체의 선두에 ‘use strict’; 를 추가하여 적용한다.

'use strict';

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

  x = 10; // ReferenceError: x is not defined
}
foo();
function foo() {
  x = 10; // 에러를 발생시키지 않는다.
  'use strict';
}
foo();

strict mode 보다는 ESLint 등을 사용하는 것을 더 권장.

20.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>
  • strict mode 스크립트와 non-strict mode 스크립트의 혼용은 오류를 발생시킬 수 있다.
  • 서드 파티 라이브러리가 non-strict mode 일 경우 전역에서 strict mode 사용은 위험하다.
  • 즉시 실행 함수로 스크립트 전체를 감싸 스코프를 구분하여 선언하는 것을 권장한다.
// 즉시 실행 함수의 선두에 strict mode 적용
(function () {
  'use strict';

  // Do something...
}());

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

  • strict mode 함수와 non-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();
}());

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';

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

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문

  • 전달된 객체를 스코프 체인에 추가.
  • 동일한 객체의 프로퍼티를 반복해서 사용할 때 객체 이름을 생략할 수 있어서 코드가 간단해지는 효과 발생.
  • 대신 성능, 가독성이 저하.
  • 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

일반 함수의 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 객체

매개변수에 전달된 인수를 재할당하여 변경해도 arguments 객체에 반영되지 않는다.

(function (a) {
  'use strict';
  // 매개변수에 전달된 인수를 재할당하여 변경
  a = 2;

  // 변경된 인수가 arguments 객체에 반영되지 않는다.
  console.log(arguments); // { 0: 1, length: 1 }
}(1));
profile
하고싶은건 많은데 시간이 없다!

0개의 댓글