function foo() {
x = 10;
}
foo();
console.log(x); // ?
전역 스코프에 x 변수 선언이 없어 ReferenceError가 발생할 것 같지만, 아무런 에러도 발생하지 않는다.
암묵적 전역 (Implicit Global)
자바스크립트 엔진은 암묵적으로 전역 객체에 x 프로퍼티를 동적 생성한다. 따라서 전역 변수처럼 사용할 수 있다.
암묵적 전역은 오류를 발생시킬 수 있기 때문에 반드시 var, let, const 키워드를 사용해야 한다.
strict mode (엄격 모드)
- ES5 부터 추가된 모드.
- 자바스크립트 언어의 문법을 더 엄격하게 적용하여 오류를 발생시킬 가능성이 높다.
- 자바스크립트 엔진의 최적화 작업에 문제를 일으킬 수 있는 코드에 명시적인 에러를 발생시킬 수 있다.
전역 또는 함수 몸체의 선두에 ‘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();
function foo() {
x = 10; // 에러를 발생시키지 않는다.
'use strict';
}
foo();
strict mode 보다는 ESLint 등을 사용하는 것을 더 권장.
전역에 적용한 strict mode는 스크립트 단위로 적용된다.
<!DOCTYPE html>
<html>
<body>
<script>
'use strict';
</script>
<script>
x = 1; // 에러가 발생하지 않는다.
console.log(x); // 1
</script>
<script>
'use strict';
y = 1; // ReferenceError: y is not defined
console.log(y);
</script>
</body>
</html>
// 즉시 실행 함수의 선두에 strict mode 적용
(function () {
'use strict';
// Do something...
}());
(function () {
// non-strict mode
var lеt = 10; // 에러가 발생하지 않는다.
function foo() {
'use strict';
let = 20; // SyntaxError: Unexpected strict mode reserved word
}
foo();
}());
선언하지 않은 변수를 참조하면 ReferenceError 발생.
(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.
}());
중복된 매개변수 이름을 사용하면 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));
}());
with문
- 전달된 객체를 스코프 체인에 추가.
- 동일한 객체의 프로퍼티를 반복해서 사용할 때 객체 이름을 생략할 수 있어서 코드가 간단해지는 효과 발생.
- 대신 성능, 가독성이 저하.
- with문의 사용은 비권장사항.
(function () {
'use strict';
// SyntaxError: Strict mode code may not include a with statement
with({ x: 1 }) {
console.log(x);
}
}());
일반 함수의 this는 undefined로 바인딩.
생성자 함수가 아닌 일반 함수에서는 this를 사용할 필요가 없기 때문.
(function () {
'use strict';
function foo() {
console.log(this); // undefined
}
foo();
function Foo() {
console.log(this); // Foo
}
new Foo();
}());
매개변수에 전달된 인수를 재할당하여 변경해도 arguments 객체에 반영되지 않는다.
(function (a) {
'use strict';
// 매개변수에 전달된 인수를 재할당하여 변경
a = 2;
// 변경된 인수가 arguments 객체에 반영되지 않는다.
console.log(arguments); // { 0: 1, length: 1 }
}(1));