ES5에 추가된 기능으로, 잠재적인 오류를 발생시킬 가능성이 높거나 자바스크립트 엔진의 최적화 작업에 문제를 일으킬 수 있는 코드에 명시적인 에러를 발생시킨다.
예를들어, 아래코드에서 어떤 스코프에도 x 변수가 존재하지 않기 때문에 자바스크립트 엔진은 암무적으로 전역 객체에 x 프로퍼티를 동적생성한다. (암묵적 전역)
function foo() {
x=10;
}
foo();
console.log(x) // 10
개발자의 의도와 상관없이 발생한 암묵적 전역은 오류를 발생시킬 원인이 될 수 있고, Strict Mode를 사용하면 이를 방지할 수 있다.
ES6에서 도입된 클래스와 모듈은 기본적으로 Strict Mode가 적용된다.
Strict Mode 대신 ESLint 같은 린트 도구를 사용해도 비슷한 효과를 얻을 수 있다. ESLint는 Strict Mode가 제한하는 오류를 방지할 뿐만 아니라 코딩 컨벤션을 설정 파일 형태로 정의하고 강제할 수 있어 협업에서 아주 유용하다.
Strict Mode를 사용하려면 전역의 선두 또는 함수 몸체의 선두에 'use strict'를 추가한다.
'use strict'
function foo() {
x=10; // ReferenceError: x is not defined
}
foo();
function foo() {
'use strict'
x=10; // ReferenceError: x is not defined
}
foo();
만약, 'use strict'를 선두에 위치시키지 않으면 strict mode가 제대로 동작하지 않는다.
요약하면, Strict Mode는 즉시 실행 함수로 감싼 스크립트 단위로 적용하는것이 바람직하다.
전역에 Strict Mode 사용을 피해라
스크립트 별로 Strict Mode 사용을 다르게 하면 오류를 발생시킬 수 있다. 따라서 즉시실행 함수로 스크립트 전체를 감싸 스코프를 구분해 적용한다.
(funstion () {
'use strict';
// Do something...
})()
함수 단위로 Strict Mode 사용을 피해라
함수별로 Strict Mode 사용을 다르게 하는것으 바람직하지 않으며, 함수별로 일일이 Strict Mode를 적용하는 것은 번거롭다.
(funstion () {
var let = 10;
function foo() {
'use strict';
let = 20; // SyntaxError: Unexpected strict mode reserved word
}
foo();
// Do something...
})()
(function() {
'use strict';
x = 1; // ReferenceError: x is not defined
})()
(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
})()
(function() {
'use strict';
function foo(x, x) {
return x + x; // SyntaxError: Duplicate parameter name not allowed in this context
}
console.log(foo(1, 2))
})()
(function() {
'use strict';
// SyntaxError: Strict mode code may not include a with statement
with({ x: 1 }) {
console.log(x)
}
})()
Window 객체가 반환된다.(function () {
'use strict';
function foo(x, x) {
console.log(this) // undefined
}
foo();
function Foo() {
console.log(this); // Foo
}
new Foo();
})();
(function (a) {
'use strict';
a = 2;
console(arguments); // {0:1, length: 1}
})(1);
린트 도구(ESLint 등)를 사용하자