20장 strict mode

20.1 strict mode란?(20-01)

  • strict mode = 엄격 모드

  • 아래상황에서 엔진은 암묵적으로 전역에 x 프로퍼티 동적생성 이는 원하지 않은 문제가 발생

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

console.log(x); // ? : 10

20.2 strict mode의 적용(20-02)

  • 사용법
'use strict'; // 사용방식

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

20-03

  • 해당 함수와 중첩 함수에 적용
function foo() {
  'use strict';

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

20-04

  • 선두에 위치시키지 않으면 제대로 동작 X
function foo() {
  x = 10; // 에러를 발생시키지 않는다.
  'use strict';
}
foo();

20.3 전역에 strict mode를 적용하는 것은 피하자(20-05)

  • 스크립트 단위로 적용되기 때문
<!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>

20-06

  • 아래처럼 사용하자
// 즉시 실행 함수의 선두에 strict mode 적용
(function () {
  'use strict';

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

20.4 함수 단위로 strict mode를 적용하는 것도 피하자(20-07)

  • 아까처럼 선두에 위치시키지 않으면 소용없음
(function () {
  // non-strict mode
  var lеt = 10; // 에러가 발생하지 않는다.

  function foo() {
    'use strict';

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

20.5 strict mode가 발생시키는 에러

20.5.1 암묵적 전역(20-08)

  • 선언하지 않은 변수 참조시 ReferenceError
(function () {
  'use strict';

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

20.5.2 변수, 함수, 매개변수의 삭제(20-09)

  • 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 매개변수 이름의 중복(20-10)

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

  • with문을 사용하면 SyntaxError 애초에 사용 비추천(가독성 떨어짐)
(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(20-12)

  • strict mode에서 일반 함수로 호출하면 this는 undefined가 바인딩(생성자 함수가 아닌이상 사용할 필요 없어서) 에러는 발생X
(function () {
  'use strict';

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

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

20.6.2 arguments 객체(20-13)

  • strict mode에서 매개변수에 전달된 인수를 재할당하여 변경해도 arguments 객체에 반영되지 않는다
(function (a) {
  'use strict';
  // 매개변수에 전달된 인수를 재할당하여 변경
  a = 2;

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

댓글남기기