새소식

JavaScript

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

  • -

1. strict mode 란?

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

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

console.log(x); // ?

console.log(x)는 전역변수에 x 가 없으나, 자바스크립트 엔진이 전역객체에 암묵적으로 x 프로퍼티를 동적으로 추가한다. 이는 전역변수처럼 사용이 가능한데, 이를 암묵적 전역이라 한다.

 

위와 같은 현상은 개발자의 의도와 다르게 동작할 우려가 있으므로, var, let, const 키워드를 사용하여 변수를 선언한 다음에 사용해야한다.

 

혹은 ESLint 를 사용할 것

 

 

2. strict mode의 사용

strict mode를 적용하려면 전역의 선두 또는 함수 몸체의 선두에 'use strict'; 를 추가한다. 전역의 선두에 추가하면 스크립트 전체에 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();

 

 

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 인 경우도 있기 때문에 전역에 strict mode를 적용하는 것은 바람직하지 않다. (-> 이러한 경우 즉시 실행 함수로 스크립트 전체를 감싸서 스코프를 구분하고 즉시 실행 함수의 선두에 strict mode를 적용한다.)

 

 

 

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

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

 

 

5. strict mode가 발생시키는 에러

 

5-1. 암묵적 전역 

선언하지 않은 변수를 참조하면 RefenceError가 발생한다

(function () {
  'use strict';

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

 

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

 

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

 

5-4. with문의 사용

with문을 사용하면 SyntaxError가 발생한다. 

with문은 전달된 객체를 스코프 체인에 추가하는데, 동일한 객체의 프로퍼티를 반복해서 사용할 때 객체 이름을 생략할 수 있어 코드가 간단해진다. 하지만 성능과 가독성이 나빠져 사용하지 않는 것이 좋다. 

(function () {
  'use strict';

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

 

6. strict mode 적용에 의한 변화 

 

6-1. 일반함수의 this

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

 

생성자 함수가 아닌 일반함수 내부에서는 this를 사용할 필요가 없기 때문이다.

function () {
  'use strict';

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

  function Foo() {
    console.log(this); // Foo
  }
  new Foo();
}());

 

 

6-2. arguments 객체

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

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

  // 변경된 인수가 arguments 객체에 반영되지 않는다.
  console.log(arguments); // { 0: 1, length: 1 }
}(1));
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.