strict mode

heejung·2022년 4월 8일
0

deep dive

목록 보기
17/20
  • 자바스크립트 언어의 문법을 좀 더 엄격히 적용
  • 오류 발생 가능성이 높은 코드에 대해 명시적인 에러를 발생시킴

ESLint와 같은 린트 도구를 사용하면 strict mode보다 더욱 강력한 효과를 얻을 수 있다.

린트 도구

정적 분석 기능을 통해 소스코드를 실행하기 전에 소스코드를 스캔하여 문법적 오류만이 아닌 잠재적 오류까지 찾아내고 오류의 원인을 리포팅해주는 도구


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

  • 전역 strict mode

    전역에 적용한 strict mode는 다른 스크립트에 영향을 주지 않고 해당 스크립트에 한정되어 적용된다. 그러나 strict mode 스크립트와 non-strict mode 스크립트를 혼용하면 오류를 발생시킬 수 있다.

  • 함수 단위의 strict mode

    어떤 함수는 strict mode를 적용하고 어떤 함수는 strict mode를 적용하지 않는 것은 바람직하지 않다. 또한 모든 함수에 일일이 strict mode를 적용하는 것 역시 번거로운 일이다.


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

(function() {
  `use strict`;
  
  // ...
}());

strict mode 가 발생시키는 에러

암묵적 전역

  • 선언하지 않은 변수 참조 시 ReferenceError 발생
(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.
  
  funcion 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));
}());

with 문의 사용

  • with 문 사용 시 SyntaxError 발생
  • with 문 : 전달된 객체를 스코프 체인에 추가함 (성능과 가독성이 나빠 사용하지 않는 것이 좋음)
(function() {
  `use strict`;
  
  // SyntaxError: Strict mode code may not include a with statement
  with({ x: 1 }) {
    console.log(x);
  }
}());

strict mode 적용에 의한 변화

일반 함수의 this

  • strict mode에서 일반 함수 호출 시 this에 undefined 바인딩
    (생성자 함수가 아닌 함수 내부에서는 this를 사용할 필요가 없기 때문)
(function() {
  `use strict`;
  
  function foo() {
    console.log(this); // undefined
  }
  foo(); // 일반 함수로 호출
  
  function Foo() {
    console.log(this); // Foo
  }
  new Foo(); // 생성자 함수로 호출
}());

arguments 객체

  • strict mode에서는 매개변수에 전달된 인수를 재할당해도 arguments 객체에 반영되지 않음
(function(a) {
  `use strict`;
  // 매개변수에 전달된 인수 재할당
  a = 2;
  
  // 변경된 인수가 arguments 객체에 반영되지 않음
  console.log(arguments); // { 0: 1, length: 1 }
}(1));
profile
프론트엔드 공부 기록

0개의 댓글