
RefferenceError를 발생시킬 것 같지반 JS 엔진은 암묵적으로 전역 객체에 x 프로퍼티를 동적 생성함.function foo() {
x = 10;
}
foo();
console.log(x);strict mode(엄격 모드)가 추가됨.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();
strict mode는 스크립트 단위로 적용됨.strict mode와 non-strict mode 스크립트를 혼용하는 것은 오류를 발생시킬 수 있고, 특히 서드파티 라이브러리를 사용하는 경우 라이브러리가 non-strict mode인 경우도 있기 때문에 전역에 strict mode를 적용하는 것은 바람직 하지 않음. (이러한 경우는 즉시 실행 함수로 스크립트 전체를 감싸서 스코프를 구분하고 즉시 실행 함수의 선두에 strict mode를 적용)(function () {
'use strict';
// Do something...
}());strict mode를 적용할 수 있으나, 어떤 함수는 적용하고 어떤 함수는 미적용 하는 것은 바람직하지 않으며 모든 함수에 일일이 strict mode를 적용하는 것은 번거로운 일임. 그리고 strict mode가 적용된 함수가 참조할 함수 외부의 컨텍스트에 strict mode를 적용하지 않는다면 이 또한 문제를 발생시킬 수 있음.strict mode는 즉시 실행 함수로 감싼 스크립트 단위로 적용하는 것이 바람직함.(function () {
'use strict';
x = 1;
console.log(x); // ReferenceError: x is not defined
}());
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.
}());(function () {
'use strict';
// SyntaxError: Duplicate parameter name not allowed in this context
function foo(x, x) {
return x + x;
}
console.log(foo(1, 2));
}());with문을 사용하면 SyntaxError가 발생.with문은 전달된 객체를 스코프 체인에 추가한다. 동일한 객체의 프로퍼티를 반복해서 사용할 때 객체 이름을 생략할 수 있어서 코드가 간단해지는 효과가 있지만, 성능과 가독성이 나빠지므로 사용하지 않는 것이 좋음.(function () {
'use clinet';
// SyntaxError: Strict mode code may not include a with statement
with({ x: 1 }) {
console.log(x);
}
}());strict mode에서 함수를 일반 함수로서 호출하면 this에 undefined가 바인딩 됨.this를 사용할 필요가 없기 때문. (에러는 발생하지 않음)(function () {
'use strict';
function foo() {
console.log(this); // undefined
}
foo();
function Foo() {
console.log(this); // Foo
}
new Foo();
}());strict mode에서는 매개변수에 전달된 인수를 재할당하여 변경해도 arguments 객체에 반영되지 않음.(function (a) {
'use strict';
// 매개변수에 전달된 인수를 재할당하여 변경
a = 2;
// 변경된 인수가 arguments 객체에 반영되지 않음
console.log(arguments); // { 0: 1, length: 1 }
}(1));