JS Deep Dive - strict mode

이승윤·2022년 11월 30일
1

Strict Mode


strict mode란?

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

ESLint와 같은 린트 도구를 사용해도 이와 같은 효과를 얻을 수 있다. 린트 도구는 정적 분석 기능을 통해 소스코드를 실행하기 전에 소스코드를 스캔하여 문법적 오류만이 아니라 잠재적 오류까지 찾아내고 오류의 원인을 리포팅해주는 유용한 도구다.

strict mode의 적용

'use strict'; // mode 적용

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

// 함수 몸체의 선두에 추가하면 해당 함수와 중첩 함수에 strict mode가 적용된다.
function bar() {
  'use strict';
  
  x = 10; // ReferenceError
}

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

strict mode가 발생시키는 에러


암묵적 전역

(function () {
  'use strict';
  
  x = 1;
  console.log(x); // ReferenceError: x is not defined
}());

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

(function () {
  'use strict';
  
  var x = 1;
  delete x; // 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문의 사용

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

Strict mode 적용에 의한 변화


일반 함수의 this

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

arguments 객체

(function (a) {
  'use strict';
  // 매개변수에 전달된 인수를 재할당하여 변경
  a = 2;
  
  // 변경된 인수가 arguments 객체에 반영되지 않는다.
  console.log(arguments); // { 0: 1, length: 1 }
}(1));
profile
항상 꿈꾸는 개발자

2개의 댓글

comment-user-thumbnail
2022년 12월 2일

혹시 과제하면서 스트릭 모드를 적용하셨나용~?!?

답글 달기
comment-user-thumbnail
2022년 12월 5일

잘 보고 갑니다.

답글 달기