FrontEnd/Deep Dive

[JS] DeepDive(20) strict mode

728x90

 

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

console.log(x); // ?

 

foo 함수 내에서 선언하지 않은 x변수에 값 10을 할당했다. 따라서 ReferenceError를 발생시킬 것 같지만 JS는 위 경우 암묵적으로 전역 객체에 x프로퍼티를 동적으로 생성한다.

 

이러한 개발자의 의도와 상관없는 암묵적 전역은 오류를 발생시킬 원인이 될 수 있다. 따라서 var,let,const 등 키워드를 활용해서 변수를 선언하는것이 좋지만 사람은 누구나 실수를 할 수 있다.

 

 

이런 상황을 막아주기 위해서 strict mode가 추가되었다.물론 ESLink와 같은 도구를 활용할 수도 있다.

 

 

 

strict mode의 적용

 

'use strict'를 전역의 선두 혹은 함수 몸체의 선두에 추가하면 된다.

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

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

 

 

 

전역에 적용한 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>

 

strictmode오 ㅏnon-strict mode를 혼용하는것은 물론 피해야 한다. 하지만 외부 서드파티 라이브러리를 사용하는 경우 라이브러리가 non-strict mode인 경우도 있기 때문에 전역에 strict mode를 적용하는것은 바람직하지 않다.

 

이런 경우 즉시 실행 함수로 스크립트 전체를 감싸여 스코프를 구분한 이후 strict mode를 적용하자.

 

 

// 즉시 실행 함수의 선두에 strict mode 적용
(function () {
  'use strict';

  // Do something...
}());

 

 

함수단위로 strictmode를 적용하는것도 가능하다고 했지만 이 또한 권장되는 방법은 아니다 모든 함수에 use strict를 적용하는것은 번거롭고 특정 함수들에만 strict mode 를 적용하는것도 바람직하지 않다. 따라서 strict mode는 즉시 실행 함수로 감싼 스크립트 단위로 적용하자.

 

 

 

 

strict mode가 발생시키는 에러

 

1. 암묵적 전역

 

(function () {
  'use strict';

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

 

 

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

 

delete 연산자로 변수,함수,매개변수를 삭제하는 경우

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

 

 

3. 매개변수 이름의 중복

 

(function () {
  'use strict';

  //SyntaxError: Duplicate parameter name not allowed in this context
  function foo(x, x) {
    return x + x;
  }
  console.log(foo(1, 2));
}());

 

 

 

4. with문의 사용

 

with문은 전달된 객체를 스코프 체인에 추가한다. with문은 동일한 객체의 프로퍼티를 반복해서 사용하는 경우 객체 이름을 생략하여 코드가 간단해지지만 성능,가독성이 낮아지는 문제가 있으니 사용하지 않기로 하자.

(function () {
  'use strict';

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

 

 

 

 

 

 

strict mode 적용에 의한 변화

 

1. 일반함수의 this

 

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

 

(function () {
  'use strict';

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

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

 

 

 

2. arguments 객체

 

매개변수에 전달된 인수를 재할당해도 arguments에 재할당되지 않는다.

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

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90

'FrontEnd > Deep Dive' 카테고리의 다른 글

[JS] DeepDive(22) this  (0) 2023.08.19
[JS] DeepDive(20) 빌트인 객체  (0) 2023.08.17
[JS] DeepDive(19) 프로토타입 -2  (0) 2023.08.13
[JS] DeepDive(19) 프로토타입 - 1  (0) 2023.08.12
[JS] DeepDive(18) 함수와 일급 객체  (0) 2023.08.12