📌 https://poiemaweb.com/ 를 참고하여 작성한 글입니다.
Strict Mode는 코드에 문법을 보다 엄격히 적용하는 방법입니다.
strict mode를 적용하려면 전역의 선두 또는 함수 몸체의 선두에
'use strict';
를 추가한다.
strict mode 스크립트와 non-strict mode 스크립트를 혼용하는 것은 오류를 발생시킬 수 있다. 특히 외부 서드 파티 라이브러리를 사용하는 경우, 라이브러리가 non-strict mode일 경우도 있기 때문에 전역에 strict mode를 적용하는 것은 바람직하지 않다.
어떤 함수는 strict mode를 적용하고 어떤 함수는 strict mode를 적용하지 않는 것은 바람직하지 않으며 모든 함수에 일일이 strict mode를 적용하는 것은 번거로운 일이다. 그리고 strict mode가 적용된 함수가 참조할 함수 외부의 컨텍스트에 strict mode를 적용하지 않는다면 이 또한 문제가 발생할 수 있다.
즉시 실행 함수로 스크립트 전체를 감싸서 스코프를 구분하고 즉시 실행 함수의 선두에 strict mode를 적용한다.
(function () {
// non-strict mode
var lеt = 10; // 에러가 발생하지 않는다.
function foo() {
'use strict';
let = 20; // SyntaxError: Unexpected strict mode reserved word
}
foo();
}());
(function () {
'use strict';
x = 1;
console.log(x); // ReferenceError: x is not defined
}());
(function () {
'use strict';
//SyntaxError: Duplicate parameter name not allowed in this context
function foo(x, x) {
return x + x;
}
console.log(foo(1, 2));
}());
(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.
}());
등등..