🚀 94sssh
Published on

2024.06.04

[딥다이브] - 20. strict mode

20.1. strict mode란?

암묵적 전역: 자바스크립트 엔진이 암묵적으로 전역 객체에 프로퍼티를 동적 생성하여 전역 변수처럼 사용할 수 있는 것

개발자의 의도와 상관없이 발생한 암묵적 전역은 오류를 발생시킬 가능성이 크므로, 반드시 var, let, const 키워드를 사용하여 변수를 선언한 다음 사용해야 한다. 그렇지만 오타 등 실수는 언제나 발생할 수 있어, 이러한 잠재적인 오류를 방지하기 위해 ES5부터 strict mode(엄격 모드)가 추가되었다.

ESLint 같은 린트 도구를 사용하면 더 강력한 효과를 볼 수 있어 strict mode보다 린트 도구의 사용이 선호된다.

20.2. strict mode의 적용

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

'use strict'

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

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

function foo() {
  'use strict'

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

20.3. 전역에 strict mode를 적용하는 것은 피하자

전역에 적용한 strict mode는 스크립트 단위로 적용된다. 스크립트 단위로 적용된 strict mode는 다른 스크립트에 영향을 주지 않고 해당 스크립트에만 적용된다. strict mode인 스크립트와 non-strict mode 스크립트를 혼용하는 것은 바람직하지 않다.

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

어떤 함수는 strict mode를 적용하고 어떤 함수는 그렇지 않는 것 또한 바람직하지 않다. strict mode가 적용된 함수가 참조할 외부 컨텍스트에 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'

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

중복된 매개변수 이름을 사용하면 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))
})()

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

20.6. strict mode 적용에 의한 변화

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

20.6.2. arguments 객체

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

;(function (a) {
  'use strict'
  a = 2

  console.log(arguments) // [Arguments] { '0': 1 }
})()