Strict mode(엄격 모드)

NSH·2022년 5월 9일
0

개인적으로 공부하면서 블로그를 작성하고 있으므로 내용이 정확하지 않을 수 있습니다.
잘못된 부분은 지적해주시면 개발자로서 성장하는데 많은 도움이 될 것 같습니다. 😀

strict mode 란?

ES5에서 등장한 strict mode는 자바스크립트 코드에 더욱 엄격한 오류 검사를 적용해주며 스크립트나 함수의 최상단에 'use strict' 지시어를 사용하여 선언할 수 있다.

strict mode 적용

스크립트 최상단에 선언하면 스크립트 전체에 strick mode가 적용되며 주의 할 사항은 스크립트 최상단에 위치하지 않으면 strict mode가 정상적으로 활성화되지 않을 수 있다.

'use strict' 지시어는 스크립트 최상단에 위치하지 않으므로 무시된다.

alert('alert'); 

'use strict'

'use strict'를 스크립트 최상단에 선언되어 스크립트 전체에 strict mode가 적용된다.

'use strict'

function fun() {
	a = 100; // ReferenceError: a is not defined;
}

fun();

'use strict'를 함수의 최상단에 선언하면 해당 함수와 중첩된 내부 함수에 strict mode가 적용된다.

function fun() {
  'use strict';

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

strict mode는 전역에 적용하지 말자

전역에 적용한 strict mode는 스크립트 단위로 적용된다.

<html>
<body>
	<script>
    	'use strict'
    </script>
    <script>
    	// 해당 스크립트에는 strict mode가 적용되지 않아서 선언되지 않은 변수를
        // 참조했지만 에러가 발생하지 않는다.
    	x = 1; 
        console.log(x);
    </script>
    <script>
      'use strict';

      y = 1; // ReferenceError: y is not defined
      console.log(y);
  	</script>
</body>
</html>

위와 같이 스크립트 단위로 적용된 strict mode는 다른 스크립트에 영향을 주지 않는다.

외부 라이브러리를 사용하는 경우, 라이브러리가 strict mode를 사용하지 않을 수 있기 때문에 전역에 strict mode를 적용하는 방법은 바람직하지 않다.

이런 경우에는 즉시 실행 함수로 스크립트 전체를 감싸서 스코프를 구분하고 즉시 실행 함수의 선두에 strict mode를 적용하면 된다.

(function () {
  'use strict';
}());

strict mode가 발생시키는 에러

strict mode를 적용했을 때 에러가 발생하는 대표적인 사례이다.

암묵적 전역 변수

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

(function () {
	'use strict'
    
    x = 1;
    console.log(x); // ReferenceError: x is not defined
}())

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

(function () {
	'use strict'
    
    var x = 1;
  	// 변수 삭제
  	// SyntaxError: Delete of an unqualified identifier in strict mode.
  	delete x; 
  	
  	function foo(a) {
      	// 매개변수 삭제
      	// SyntaxError: Delete of an unqualified identifier in strict mode.
    	delete a;
    }
  
  	// 함수 삭제
  	// SyntaxError: Delete of an unqualified identifier in strict mode.
  	delete foo;
}())

매개변수 이름의 중복

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

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

일반 함수의 this

strict mode가 적용되지 않았다면 일반 함수의 this는 window가 바인딩 되겠지만, 아래 코드는 strict mode이므로 undefined가 바인딩된다.

(function () {
  'use strict';

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

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

결론

자바스크립트 코드에 더욱 엄격한 오류 검사를 적용시켜 자바스크립트 엔진의 최적화 작업에 문제를 일으킬 수 있는 코드에 명시적인 에러를 발생시켜주므로 코드를 작성함에 있어서 많은 도움이 될 것 같다.

참고
https://ko.javascript.info/strict-mode
http://www.tcpschool.com/javascript/js_exception_strict
https://poiemaweb.com/js-strict-mode

profile
잘 하고 싶다.

0개의 댓글