본문 바로가기
개인공부/모던 자바스크립트 Deep Dive

20장 strict mode

by 강물둘기 2023. 1. 4.

* 아래 내용은 이웅모 저자님의   모던 자바스크립트 Deep Dive 책(위키북스)을 정리한 내용입니다.

   저작권에 문제가 된다면 삭제하도록 하겠습니다.

 

20.1 strict mode란?

잠재적인 오류를 발생시키기 어려운 개발환경을 만들기위해 ES5에서 strict mode(엄격 모드)가 추가되었다.

 

20.2 strict mode의 적용

전역의 선두 또는 함수 몸체의 선두에 'use strict';를 추가한다. 

'use strict';

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

 

20.3 전역에 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를 적용하는 것은 바람직 하지 않다.

 

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

 strict mode는 즉시 실행 함수로 감싼 스크립트 단위로 적용하는 것이 바람직하다.

 

20.5 strict mode가 발생시키는 에러

 20.5.1 암묵적 전역

(function () {
  'use strict';

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

20.5.2 변수, 함수, 매개변수의 삭제

(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 매개변수 이름의 중복

(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문은 전달된 객체를 스코프체인에 추가하는데 사용하지 않는 것을 권장한다.

(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가 바인딩된다.

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

 

Reference

- 이웅모 ,  모던 자바스크립트 Deep Dive , 위키북스 , 2020 

'개인공부 > 모던 자바스크립트 Deep Dive' 카테고리의 다른 글

23장 실행컨텍스트(2)  (0) 2023.01.06
23장 실행 컨텍스트(1)  (0) 2023.01.05
19장 프로토타입(3)  (0) 2023.01.04
19장 프로토타입(2)  (0) 2023.01.03
19장 프로토타입(1)  (0) 2023.01.02

댓글