[모던 JS Deep Dive] 20장. strict mode

Jinny·2023년 10월 30일

20.1 strict mode

strict mode(엄격 모드)는 JS 언어의 문법을 좀 더 엄격히 적용하여 오류를 발생시킬 가능성이높거나 JS 엔진의
최적화 작업에 문제를 일으킬 수 있는 코드에 명시적인
에러를 발생시킨다.

ES6에서 도입된 클래스와 모듈은 기본적으로 strict mode가 적용된다.

20.2 strict mode의 적용

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

'use strict';

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

함수 몸체의 선두에 추가하면 해당 함수와 중첩 함수에 strict mode가 적용된다.

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

코드의 선두에 use strict;를 위치시키지 않으면
strict mode가 제대로 동작하지 않는다.

function foo() {
  a = 10;  //에러 발생 ❌
  'use strict';
}
foo();

20.3 전역에 strict mode 적용은 피하자

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

<script>
   'use strict';
</script>
<script>
  a = 1; //에러 발생 ❌
  console.log(a); // 1 
</script>
<script>
  'use strict';
   b = 5; //Reference Error: b is not defined
</script>
  • 스크립트 단위로 적용된 strcit mode는 다른 스크립트에 영향을 주지 않고 해당 스크립트에 한정되어 적용된다.

  • strict mode 스크립트와 non-strict mode 스크립트를 혼용하는 것은 오류를 발생시킬 수 있다.

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

어떤 함수는 strict mode를 적용하고 다른 함수는 strict mode를 적용하지 않는 것은 바람직하지 않다.

(function() {
  //non-strict mode
  var let = 10; // 에러 발생 ❌
  
  function foo() {
    'use strict';
     let = 20; //SyntaxError : Unexpected strict mode reserved word
  }
  foo();
}());

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

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';
   let x = 1;
  function foo(a){
   delete a; //SyntaxError: Delete of an unqualified identifier in strict mode.
  }
}());
foo(); 

20.5.3 매개변수 이름의 중복

중복된 매개변수 이름을 사용하면 SyntaxError가 발생한다.

function foo(x,x) {
  'use strict';
   return x*x;
}
foo(3,3); // Duplicate parameter name not allowed in this context

20.5.4 with문의 사용

with문을 사용하면 SyntaxError가 발생한다.
with문은 동일한 객체의 프로퍼티를 반복해서 사용시 객체 이름을 생략할 수 있어 코드가 간단해지지만 성능과 가독성이 나빠서 사용하지 않는 것이 좋다.

20.6 strict mode 적용에 의한 변화

20.6.1 일반 함수의 this

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

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

20.6.2 arguments 객체

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

function foo(a) {
  'use strict';
   a = 7;
   console.log(arguments); // { 0 : 3, length: 1}
}
foo(3);

0개의 댓글