티스토리 뷰

반응형

strict mode

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


strict mode 적용

전역의 선두 또는 함수 몸체의 선두에

'use strict';

를 추가한다.

 

 

1️⃣

'use strict'; // 전역의 선두에 추가

function foo() {
  x = 10; // ReferenceError: x is not defined
}

foo();

전역의 선두에 추가하면 스크립트 전체에 적용된다.

 

 

2️⃣

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

foo();

코드의 선두에 위치시키지 않을 시 제대로 동작하지 않는다.

 

 

🚫 주의

  1. 전역에 strict mode 적용을 지양하자
  2. 함수 단위의 strict mode 적용을 지양하자

 

 


💢 strict mode가 발생시키는 에러

  1. 암묵적 전역
  2. 변수, 함수, 매개변수의 삭제
  3. 매개변수 이름의 중복
  4. with문의 사용

1️⃣ 암묵적 전역

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

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

 

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가 발생한다.

(function() {
  'use strict';
  
  // SyntaxError: Duplicate parameter name not allowed in this context
  function foo(x, x) {
    return x + x;
  }
  
  console.log(foo(1, 2));
}());

 

4️⃣ with문의 사용

with문을 사용하면 SyntaxError가 발생한다.

(function() {
  'use strict';
  
  // SyntaxError: Strict mode code may not include a with Statement
  with({ x : 1 }) {
    console.log(x);
   }
}());

 


✅ strict mode 적용에 의한 변화

 

💨 일반 함수의 this

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

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

 

 

 

좋아요는 로그인하지 않아도 누를 수 있습니다!

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함