목차

JavaScript Use Strict

  • description : JavaScipt Use Strict
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-04-12


Source of the article

"use strict"; JavaScript 코드가 “strict mode”에서 실행되어야 함을 정의합니다.

The "use strict" Directive

"use strict"지시문은 ECMAScript 버전 5에서 새로 추가되었습니다.

statement가 아니라 이전 버전의 JavaScript에서 무시되는 리터럴 표현식(literal expression)입니다.

"use strict"의 목적은 코드가 “strict mode”에서 실행되어야 함을 나타내는 것입니다.

예를 들어, strict mode에서는 선언되지 않은 변수를 사용할 수 없습니다.

Internet Explorer 9과 이하 버전을 제외한 모든 최신 브라우저는 “use strict”를 지원합니다.

모든 프로그램에서 strict mode를 사용할 수 있습니다.
선언되지 않은 변수를 사용하는 것을 방지하는 것과 같이, 더 깨끗한 코드를 작성하는 데 도움이 됩니다.

"use strict"는 그저 문자열(string)이기 때문에, IE 9에서 이해하지 못하더라도 오류가 발생하지 않습니다.

Declaring Strict Mode

스크립트 또는 함수의 시작 부분에 "use strict"를 추가하여, Strict 모드를 선언합니다.

스크립트 시작 부분에서 선언되며, 전역 범위(global scope)를 가집니다.(스크립트의 모든 코드는 strict mode에서 실행됩니다).

예제

<!DOCTYPE html>
<html>
</head>
<body>
    <h2>With "use strict"</h2>
    <h3>Using a variable without declaring it is not allowed.</h3>
    <p>Activate debugging in your browser (F12) to see the error report.</p>
    <script>
        "use strict";
        x = 3.14;   // This will cause an error (x is not defined).
    </script>
</body>
</html>

예제

<!DOCTYPE html>
<html>
</head>
<body>
    <h2>Global "use strict" declaration.</h2>
    <p>Activate debugging in your browser (F12) to see the error report.</p>
    <script>
        "use strict";
        myFunction();
        function myFunction() {
            y = 3.14;   // This will cause an error (y is not defined)
        }
    </script>
</body>
</html>


함수 내에서 선언되며 local scope를 가집니다.(함수 내부의 코드만 strict mode에 있습니다):

<!DOCTYPE html>
<html>
</head>
<body>
    <p>"use strict" in a function will only cause errors in that function.</p>
    <p>Activate debugging in your browser (F12) to see the error report.</p>
    <script>
        x = 3.14;       // This will not cause an error.
        myFunction();
        function myFunction() {
            "use strict";
            y = 3.14;   // This will cause an error (y is not defined).
        }
    </script>
</body>
</html>

The "use strict"; Syntax

strict mode를 선언하기 위한 구문은 이전 버전의 JavaScript와 호환되도록 설계되었습니다.

JavaScript 프로그램에서 숫자 리터럴 (4 + 5;) 또는 문자열 리터럴 ( “John Doe”;)을 컴파일하면 부작용이 없습니다.
단순히 존재하지 않는 변수로 컴파일하고 중지합니다.

따라서 "use strict";는 그 의미를 “이해”하는 새로운 컴파일러에게만 중요합니다.

Why Strict Mode?

Strict mode를 사용하면 “안전한(secure)” JavaScript를 더 쉽게 작성할 수 있습니다.

Strict mode는 이전에 허용된 “잘못된 구문”을 실제 오류로 변경합니다.

예를 들어, 일반 JavaScript에서 변수 이름을 잘못 입력하면 새 전역 변수(global variable)가 생성됩니다.
strict mode에서는 변수 이름을 잘못 입력하면 오류가 발생하고, 뜻하지 않게 전역 변수를 만드는 것을 불가능하게 합니다.

일반 JavaScript에서 개발자는 쓰기 불가능한 속성(non-writable properties)에 값을 할당하는 오류 피드백을 받지 않습니다.

strict mode에서는, 쓰기 불가능한 속성, getter 전용 속성, 존재하지 않는 속성, 존재하지 않는 변수 또는 존재하지 않는 오브젝트에 대한 할당은 오류를 발생시킵니다.

Not Allowed in Strict Mode

변수를 선언하지 않고 사용하는 것은 허용되지 않습니다.

"use strict";
x = 3.14;     // This will cause an error.


오브젝트도 변수입니다.

선언하지 않고 오브젝트를 사용하는 것은 허용되지 않습니다.

"use strict";
x = {p1:10, p2:20};  // This will cause an error (x is not defined).


변수 (또는 오브젝트)를 삭제할 수 없습니다.

"use strict";
var x = 3.14;
delete x;      // This will cause an error


함수 삭제는 허용되지 않습니다.

"use strict";
function x(p1, p2) {};
delete x;     // This will cause an error


매개변수(parameter) 이름을 복제하는 것은 허용되지 않습니다.

"use strict";
function x(p1, p1) {};     // This will cause an error


8진수 리터럴(Octal numeric literals)은 허용되지 않습니다.

"use strict";
var x = 010;     // This will cause an error


8진수 이스케이프 문자(Octal escape characters)는 허용되지 않습니다.

"use strict";
var x = "\010";


읽기 전용 속성(read-only property)에 작성하는 것은 허용되지 않습니다.

"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});
 
obj.x = 3.14;     // This will cause an error


가져오기 전용 속성(get-only property)에 작성한느 것은 허용되지 않습니다.

"use strict";
var obj = {get x() {return 0} };
 
obj.x = 3.14;     // This will cause an error


삭제할 수 없는 속성(undeletable property)을 삭제하는 것은 허용되지 않습니다.

"use strict";
delete Object.prototype;     // This will casue an error


eval이라는 단어는 변수로 사용할 수 없습니다.

"use strict";
var eval = 3.14;     // This will cause an error


arguments이라는 단어는 변수로 사용할 수 없습니다.

"use strict";
var arguments = 3.14;     // This will cause an error


with 스테이트먼트는 허용되지 않습니다.

"use strict";
with (Math) {x = cos(2)};     // This will causee an error


보안상의 이유로 eval()는 호출된 스코프에서 변수를 만드는 것이 허용되지 않습니다.

"use strict";
eval ("var x = 2");
alert (x);     // This will cause an error


함수의 this 키워드는 strict mode에서 다르게 작동합니다.

this 키워드는 함수를 호출한 오브젝트를 참조합니다.

오브젝트를 지정하지 않으면, strict mode의 함수는 undefined를 반환하고, 일반 모드의 함수는 전역 오브젝트(window)를 반환합니다:

"use strict";
function myFunction() {
  alert(this);     // will alert "undefined"
}
myFunction();

Future Proof!

향후 JavaScript 버전용으로 예약된 키워드는 strict mode에서 변수 이름으로 사용할 수 없습니다.

이 예약 키워드들은 아래와 같습니다:

"use strict";
var public = 1500;     // This will cause an error

Watch Out!

“use strict”지시문은 스크립트 또는 함수의 시작 부분에서만 인식됩니다.