[모던자바스크립트] 20. strict mode

이아현·2023년 9월 5일
0
post-thumbnail

✅ 1. strict mode

  • 자바스크립트 언어의 문법을 좀 더 엄격히 적용하여 오류를 발생시킬 가능성이 높거나 자바스크립트 엔진의 최적화 작업에 문제를 일으킬 수 있는 코드에 대해 명시적인 에러를 발생시킴
  • ESLint
    • 린트 도구는 정적 분석 기능을 통해 소스코드를 실행하기 전에 소스코드를 스캔하여 문법적 오류뿐만 아니라 잠재적 오류까지 찾아내고 오류의 원인을 리포팅해주는 도구

✅ 2. strict mode의 적용

  • 'use strict';를 추가
  1. 전역의 선두에 추가

    'use strict';
    
    function foo() {
        x = 10; // Reference Error: x is not defined
    }
    
    foo();
  2. 함수 몸체의 선두에 추가

    function foo() {
    	'use strict';
      
        x = 10; // Reference Error: x is not defined
    }
  • 전역에 strict mode를 적용하는 것은 피하자
    • strict mode 스크립트와 non-script mode를 혼용하는 것은 오류를 발생시킬 수도 있음
  • 함수 단위로 strict mode를 적용하는 것은 피하자
    • 어떤 함수는 strict mode를 적용하고, 어떤 함수는 적용하지 않는 것은 바람직하지 않음

✅ 3. strict mode가 발생시키는 에러

  1. 암묵적 에러
    • 선언하지 않은 변수를 참조하면 ReferenctError가 발생
     (function () {
     	'use strict';
        
        x = 1;
        console.log(x); // ReferenceError: x is undefined
     }());
  2. 변수, 함수, 매개변수의 삭제
    • 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.
    }
  3. 매개변수 이름의 중복
    • 중복된 매개변수 이름을 사용하면 SyntaxError가 발생
  4. with 문의 사용

✅ 4. strict mode 적용에 의한 변화

  1. 일반함수의 this
    • strict mode에서 함수를 일반 함수로서 호출하면 thisundefined가 바인딩
    (function () {
    	'use strict';
        
        function foo() {
        	console.log(this); // undefined
        }
        foo();
        
        function Foo() {
        	console.log(this); // Foo
        }
        new Foo();
    }());
  2. arguments 객체
    • strict mode에서 매개변수에 전달된 인수를 재할당하여 변경해도 arguments객체에 반영되지 않음
    (function (a) {
    	'use strict';
        a = 2;
        
        console.log(arguments); // { 0: 1, length: 1}
    }(1));
profile
PM을 지향하는 FE 개발자 이아현입니다 :)

0개의 댓글