모던 자바스크립트 Deep Dive : 20장 strict mode

EdLee·2022년 11월 9일

javascript

목록 보기
10/37

20장 strict mode

1. strict mode란?


function foo() {
  x = 10;
}

foo();

console.log(x); // 10....??????????
  • 변수 선언이 안되어 있는데, 변수 할당이 됐다😯

    암묵적 전역 : 변수 선언이 존재하지 않으면, JS는 전역 객체에 해당 변수와 동일하게 사용할 수 있는 프로퍼티를 동적 생성한다🤬

  • 위와 같은 js의 동작은 실수와 오류를 유발하므로, ES5부터 strict mode가 추가되었다.
  • 그런데 ESLint와 같은 정적 분석 도구를 사용하는 것이 더 좋다. strict mode는 그냥 알아만 둘 것

2. strict mode의 적용


2.1 스크립트 전체에 적용

'use strict';

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

2.2 함수에 적용

function foo() {
  'use strict';
  x = 10; // ReferenceError: x is not defined
}
foo();
  • use strict 키워드를 중간에 쓰면 적용되지 않는다

3. strict mode는 즉시 실행 함수로 감싼 스크립트 단위로 적용한다


3.1 올바른 예시

(function () {
  'use strict';
  
  function foo() {
    x = 10; // ReferenceError: x is not defined
  }
  foo();  
  
}());
  • 위와 같이 즉시 실행 함수를 통해 스코프를 분리하고 strict mode를 쓰는 것이 좋다

3.2 이유

  • 스코프 구분없이 전역에 strict mode를 적용한다면
    => strict mode가 아닌 라이브러리를 사용한다면 충돌나기 때문
  • 함수 단위로 strict mode를 적용한다면?
    => 일일히 함수마다 적용하기 불편
    =>strict mode 함수가 호출하는 외부 함수가 strict mode가 아니면 문제 발생

4. strict mode가 발생시키는 에러


4.1 암묵적 전역

  • 선언하지 않은 변수를 참조 시 에러 발생
(function() {
  'use strict';

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

}());

4.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. 

}());

4.3 매개변수 이름 중복

(function() {
  'use strict';

  function foo(x, x) { // SyntaxError: Duplicate parameter name not allowed in this context
    return x * x;
  }

}());

4.4 with 문 사용

  • with 문 : 전달 받은 객체를 스코프 체인에 추가하여, 자식 스코프 안의 구문들을 객체 스코프 하위에서 실행시킨다
(function() {
  'use strict';

  // SyntaxError: Strict mode code may not include a with statement 
  with ({ x: 1 }) {
    console.log(x);
  }
}());
// 아래와 동일
with(console) { // document 생략
  log("111");
  log("222");
  log("333");
}

// 위와 동일
console.log("111");
console.log("222");
console.log("333");

5. strict mode 적용 시 유의 점


5.1 일반 함수의 this

  • non strict mode에서 일반 함수의 this는 전역 객체
  • strict mode에서 일반 함수의 this는 undefined
  • 어차피 생성자 함수가 아닌 일반 함수 내부에서 this를 쓸 일은 없기 때문에 막아놓는듯 보인다
(function() {
  'use strict';

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

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

5.2 arguments 객체

  • strict mode에서는 매개변수로 받은 인수를 재할당해도 arguments 객체에는 반영되지 않는다
(function(a) {
  'use strict';

  a = 2;
  
  console.log(a); // 2
  console.log(arguments); // { 0: 1, length: 1}
}(1));

0개의 댓글