ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트 - Strict Mode란?
    자바스크립트 JavaScript 2022. 11. 15. 22:18

    What is Strict Mode?🧐

     

    Strict Mode는 더 secure한 javascript code를 작성할 수 있게 하는 모드입니다.
    기존에 무시되던 에러들을 throwing하고,
    최적화 작업을 어렵게 만드는 실수를 바로 잡습니다.



    0. Strict Mode의 내용 요약
    1. 에러를 표시합니다. Converting mistakes into errors.
    2. 스코프 관리를 단순화합니다. Simplifying scope management
    3. Invorking Strict Mode : 어떻게 쓰나요?
    📎 reference
    Strict Mode 한글 docs : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Strict_mode
    Strict Mode : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
    Strict Mode Code in the ECMAScript specification : https://tc39.es/ecma262/#sec-strict-mode-code
    ---
    no-op : no operate, 작동하지 않음
    sloppy mode : Strict 모드가 아닐 때, 느슨한 모드
    strict mode : Strict모드, 또는 엄격 모드

     

    0. Strict Mode의 내용 요약

      Changes in strict mode  내용
    1 changes converting mistakes into errors
    (as syntax errors or at runtime)
    런타임에 syntax 에러를 표시합니다.
    2 changes simplifying how variable references are resolved 변수 참조를 단순히 할 수 있습니다.
    3 changes simplifying eval and arguments 기존 자바스크립트 취약점을 개선합니다.
    4 changes making it easier to write "secure" JavaScript 코드를 엄격하게 작성, 관리할 수 있습니다.
    5 changes anticipating future ECMAScript evolution. 미래의 ECMA 업데이트에 대비합니다. ex) 변수 예약어

     

     


     

    1. Strict Modes는 에러를 표시합니다.

         Converting mistakes into errors.

    타임에 무시되었던 syntax 에러들을 throwing하여 실수를 줄일 수 있습니다.
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#converting_mistakes_into_errors

     

     

    👉 Assigning to undeclared variables : 실수로 글로벌 변수를 만들지 않게 합니다.

     

     

     

    👉 Failing to assign to object properties : 객체에 값 할당할 때 에러를 확인합니다.

     

    쓸 수 없는 읽기 전용일 때

    • defineProperty!
    const obj1 = {};
    Object.defineProperty(obj1, "x", { value: 42, writable: false });
    obj1.x = 9; // TypeError
    

     

    getter 전용일 때

    const obj2 = { get x() { return 17; }, };

     

    확장할 수 없는 객체일 때

    const fixed = {}; 
    Object.preventExtensions(fixed);
    fixed.newProp = "ohai"; // TypeError

     

     

    👉 plain 변수 이름을 delete할 수 없습니다.

     

    globalThis로 삭제

    "use strict";
    
    var x;
    
    delete x; // syntax error
    delete globalThis.x // ok!
    

     

     

    👉 매개변수를 중복으로 사용할 수 없습니다.

    function sum(a, a, c) { 
    	// syntax error 
        "use strict"; 
        return a + a + c; // wrong if this code ran 
    }

     

     

    👉 0-prefix를 막아줍니다! ⇒ 실수로 사용했을 때, syntax error 발생

     

    Legacy octal literals은 (0644 === 420)과 같이, 0과 8보다 작은 수로 시작하는 숫자를 8진수로 변환합니다.

     

    Strict 모드에서는 0o prefix를 사용합니다. ex) 0o10 === 8

     

     

     

    👉 Duplicate property names

     

    객체는 같은 키(속성명)을 중복해서 사용할 수 없습니다.


     

    2. Strict Mode는 스코프 관리를 단순화합니다. Simplifying scope management

     

     

    👉 with 사용 금지

     

     

    👉 non-leaking eval : eval이 주변 함수, 전역 범위 (참조하는 영역 외부)에 영향을 주지 않습니다.

     

    strict 모드에서 eval을 엄격하게 사용 가능하지만, 코드에 eval을 사용하는 것 자체가 추천되지 않습니다.(from MDN docs)

    var x = 17; 
    var evalX = eval("'use strict'; var x = 42; x;"); 
    console.assert(x === 17); 
    console.assert(evalX === 42);

     

     

    👉 Block scoped function declarations!

     

    strict모드를 꼭 사용해야될 이유 중 하나입니다. strict모드가 아니라면 block scope는 정상적으로 작동하지 않습니다.

     

     

    👉 No this substitution

     

    this로 전달된 값이 객체가 되지 않습니다.

    "use strict";
    function fun() {
      return this;
    }
    console.assert(fun() === undefined);
    console.assert(fun.call(2) === 2);
    console.assert(fun.apply(null) === null);
    console.assert(fun.call(undefined) === undefined);
    console.assert(fun.bind(true)());
    

     

     

    👉 Removal of stack-walking properties

     

    자바스크립트 stack을 walk할 수 없습니다. (보안의 이유로 더 이상 caller, arguments를 읽을 수 없습니다.)

     

     

     

    👉  Future-proofing JavaScript

     

    sloppy 모드보다 더 많은 예약어를 사용해 추후 ECMAScript 구문 확장에 대비합니다.

     

    implements, interface, let, package, private, protected, public, static, yield

     


     

    3. Invorking Strict Mode : 어떻게 쓰나요?

    사용처  사용법  주의
    스크립트 최상단에 ‘use strict’; 를 작성 js파일의 코드의 최상단
    함수 함수 스코프 최상단에 ‘use strict’ 를 작성 매개변수에 기본값이 있으면 에러
    모듈 - 자동적으로 strict mode
    클래스 - class declarations, class expressions 둘 다 body가 strict mode

     

     

    👉 스크립트에서 사용하기

     

    최상단에 ‘use strict’; 를 작성합니다.

     

    ‘use strict’는 반드시 js파일의 코드의 최상단에 위치해야 합니다.

     

    • 최상단에 위치하지 않으면 작동하지 않습니다.
    • use strict 상단의 주석은 상관 없습니다.
    // strict 모드가 적용되는 스크립트
    "use strict";
    const v = "v for vendetta"
    

     

     

    👉 함수에서 사용하기

     

    함수 스코프의 최상단에 ‘use strict’ 를 작성합니다.

    • function strictFunction () { // strict 모드가 적용되는 함수 "use strict"; ... }

     

    받는 매개변수에 기본값이 있다면 SyntaxError와 함께 작동하지 않습니다.

    • function sum (a = 1, b = 2) { // **SyntaxError**: "use strict" not allowed in function with default parameter "use strict"; return a + b; }

     

     

    👉 모듈에서 사용하기

     

    javascript modules은 자동적으로 strict mode입니다. Strict mode by default

     

     

     

    👉 클래스에서 사용하기

     

    class declarations와 class expressions의 body는 둘 다 strict mode입니다.

     

     

     

    Docs를 참고하여 Strict모드의 적용 범위과 사용법에 대해 알아보았습니다! 👵

    자세한 내용은 레퍼런스 링크를 참고해주세요.
    오류나 틀린 점이 있다면 피드백 부탁드립니다🙏 
    반응형
Designed by Tistory.