strict mode

ken6666·2024년 2월 20일
0

JS

목록 보기
16/39

strict mode란?

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

console.log(x); // 10

전역 스코프와 함수 스코프에도 x변수의 선언이 없기 때문에 에러를 발생시킬 것 같지만 자바스크립트 엔진은 암묵적으로 전역 객체에 x 프로퍼티를 동적 생성한다.

이러한 현상을 암묵적 전역이라 한다.

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

전역의 선두나 함수 몸체의 선두에 추가하면 strict mode가 적용된다.

function foo() {
  x = 10; // 에러를 발생시키지 않는다.
  'use strict';
}
foo();

코드의 선두에 use strict를 위치시키지 않으면 strict가 제대로 동작하지 않는다.

strict mode가 발생시키는 에러

암묵적 전역

(function () {
  'use strict';

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

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

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

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

delete 연산자로 변수, 함수, 매개변수를 삭제하면 에러가 발생한다.

매개변수 이름의 중복

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

with문을 사용하면 에러가 발생한다

strict mode 적용에 의한 변화

일반 함수의 this

(function () {
  'use strict';

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

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

strict mode에서 함수를 일반 함수로서 호출하면 this에 undefined가 바인딩된다. 생성자 함수가 아닌 일반 함수 내부에서는 this를 사용할 필요가 없기 때문이다. 에러는 발생하지 않는다.

arguments 객체

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

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

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

0개의 댓글