[JavaScript] 모던 자바스크립트 Deep Dive 20장 - strict mode

2022. 7. 29. 01:38Web/JavaScript


 

strict mode란?

자바스크립트의 언어의 문법을 좀 더 엄격히 적용하여 오류를 발생시킬 가능성이 높거나 자바스크립트 엔진의 최적화 잡업에 문제를 일으킬 수 있는 코드에 대해 명시적인 에러를 발생시키는 것


strict mode의 적용

전역의 선두 또는 함수의 몸체의 선두에 'use 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();


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

strict mode를 적용할 때 주의점

  • 전역에 strict mode를 적용하는 것을 피할 것
  • 함수 단위로 strict mode를 적용하는 것을 피할 것

 

전역에 strict mode를 적용

<!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>

함수 단위로 strict mode를 적용

(function (){
    // non-strict mode
    var let = 10; // 에러가 발생하지 않는다.

    function foo(){
        'use strict';

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

strict mode가 발생시키는 에러

 

암묵적 전역

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

(function(){
    'use strict';

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

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

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

매개변수 이름의 중복

중복된 매개변수 이름을 사용하면 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));
}());

 


strict mode 적용에 의한 변화

 

일반 함수의 this

strict mode에서 함수를 일반 함수로서 호출하면 this에 undefined가 바인딩된다.

생성자 함수가 아닌 일반 함수 내부에서는 this를 사용할 필요가 없기 때문이다. 에러는 발생하지 않는다.

(function(){
    'use strict';

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

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

arguments 객체

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

(function(a){
    'use strict';

    // 매개변수에 전달된 인수를 재할당하여 변경
    a = 2;

    // 변경된 인수가 arguments 객체에 반영되지 않는다.

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

}(1));