strict mode

Jeong Ha Seung·2022년 1월 16일
function foo() {
  x = 10;
}
foo();

console.log(x);

지역,전역 스코프 내에 변수 선언부가 존재하지 않기 때문에 Reference Error가 날 것 같지만 자바스크립트 엔진은 암묵적으로 전역 객체에 x 프로퍼티를 동적 생성한다. 이 때 전역 객체의 x 프로퍼티는 마치 전역 변수처럼 사용할 수 있다. 이러한 현상을 암묵적 전역이라 한다.

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();
function foo() {
  x = 10; // 에러를 발생시키지 않는다.
  'use strict'; //함수 몸체 선두에 위치시키지 않으면 strict mode가 제대로 발생하지 않는다.
}
foo();

전역에 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는 다른 스크립트에 영향을 주지 않고 해당 스크립트에 한정되어 적용된다.

함수 단위로 strict mode 사용 피하기

(function () {
  // non-strict mode
  var lеt = 10; // 에러가 발생하지 않는다.
  
  function foo() {
    'use strict';

    let = 20; // SyntaxError: Unexpected strict mode reserved word
  }
  foo();
}());

strict mode가 발생시키는 에러

암묵적 전역

(function () {
  'use strict';

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

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

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

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

매개변수 이름의 중복

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

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

profile
블로그 이전했습니다. https://morethan-haseung-log.vercel.app

0개의 댓글