Total: Today: Yesterday:
연구소/이것저것 | 2016. 4. 18. 22:01 | Posted by 자수씨


최근에 나오는 라이브러리를 보면 ```"use strict"``` 라는 문구가 자주 보입니다.


strict 미국·영국 [strɪkt]

1. (규칙 등이) 엄격한

2. (사람이 남에 대해) 엄격한

3. (사람이 자신의 종교・신념 등에 대해) 엄격한


- 네이버 어학사전


사전에서 볼 수 있듯이 무언가 엄격하게 사용한다는 의미로 생각이 되는데, 간단하게 알아보려 합니다.



#h3 strict 모드의 정의


strict 모드로 설정하는 방법은 간단합니다. 코드 앞쪽에 ```"use strict"``` 를 추가하는 것 입니다.

### js


"use strict";

x = 3.14;       // This will cause an error (x is not defined)

위의 예제를 실행하면 콘솔 창에 아래와 같은 오류가 찍히게 됩니다.


Uncaught ReferenceError: x is not defined


정의가 되지 않은 x 로 인해 정상적으로 동작을 하지 않습니다.


### js


"use strict";

myFunction();


function myFunction() {

    y = 3.14;   // This will also cause an error (y is not defined)

}

위의 예제도 y 가 정의되지 않아 정상적으로 실행되지 않습니다.




### js


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)

}

위의 예제는 x 가 사용되기 전에는 ```"use strict"``` 가 선언되지 않았으므로 y 에 대해서만 오류가 발생합니다.



#h3 왜 strict 모드를 사용하는가?


"보안" 자바스크립트를 작성하는 쉬운 방법이기 때문입니다. 다른 이유는 "올바르지 않은 문법" 을 사전에 검출할 수 있습니다.


strict 모드는 쓰기금지 프로퍼티의 정의, getter 전용 프로터피, 존재 하지 않는 프로퍼티, 존재하지 않는 변수, 존재하지 않는 객체에 대해 에러를 발생시킵니다.



#h3 strict 모드에서 허용되지 않는 문법


1. 정의되지 않은 변수의 사용

### js


"use strict";

x = 3.14;                // This will cause an error (x is not defined)

### js


"use strict";

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


2. 변수나 객체의 삭제

### js


"use strict";

var x = 3.14;

delete x;                // This will cause an error


3. 함수 파라미터에 중복된 이름

### js


"use strict";

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


4. 8진수

### js


"use strict";

var x = 010;             // This will cause an error


5. 이스케이프 문자

### js


"use strict";

var x = \010;            // This will cause an error


6. 읽기전용 프로퍼티에 값 설정

### js


"use strict";

var obj = {};

Object.defineProperty(obj, "x", {value:0, writable:false});


obj.x = 3.14;            // This will cause an error


7. 조회 전용 프로퍼티에 값 설정

### js


"use strict";

var obj = {get x() {return 0} };


obj.x = 3.14;            // This will cause an error


8. ```eval```, ```arguments``` 문자열에 대한 변수로의 사용

### js


"use strict";

var eval = 3.14;         // This will cause an error

var arguments = 3.14;    // This will cause an error


9. ```with``` 사용

### js


"use strict";

with (Math){x = cos(2)}; // This will cause an error


10. ```eval()``` 에 정의된 변수 사용

### js


"use strict";

eval ("var x = 2");

alert (x);               // This will cause an error



#h3 References

http://www.w3schools.com/js/js_strict.asp