20.1 strict mode란?
function foo(){
x=10;
}
foo();
console.log(x);
변수의 선언이 없기때문에 ReferenceError가 발생할 것 같지만 JS엔진이 전역객체에 x프로퍼티를 동적으로 생성하여(암묵전 전역)10을 출력, 이는 오류의 원인이 될 수 있음
이런 현상의 방지를 위한 strict mode로 명시적인 에러를 발생시킴, 또는 ESLint 사용(문법적오류, 잠재적오류, 오류 원인 리포팅)
20.2 strict mode의 적용
//1. 전역의 선두
'use strict';
function foo(){
//2. 함수 몸체의 선두
'use strict';
x=10; //ReferenceError : x is not defined
}
foo();
20.3 전역에 strict mode를 적용하는 것은 피하자
스크립트 단위로 적용되는 strict mode, 외부 서드파티 라이브러리를 사용하는 경우 전역에 적용된 strict mode는 오류를 발생시킬 수 있음
20.4 함수 단위로 strict mode를 적용하는 것도 피하자
strict mode가 적용된 함수가 참조할 함수 외부의 컨텍스트에 strict mode가 적용되지않는것은 오류가 발생할 수 있음
(function (){
//non-strict mode
var let = 10; //에러x
function foo(){
'use strict';
let = 20; //SyntaxError
}
foo();
}());
-> strict mode는 즉시실행 함수로 감싼 스크립트 단위로 적용하는 것이 바람직
20.5 strict mode가 발생시키는 에러
20.5.1 암묵적 전역 : 선언하지 않은 변수를 참조하면 ReferenceError
(function(){
'use strict';
x=1;
console.log(x); //ReferenceError
}());
20.5.2 변수, 함수, 매개변수의 삭제 : delete연산자로 변수, 함수, 매개변수 삭제시 SyntaxError
(function(){
'use strict';
var x=1;
delete x; //SyntaxError
function foo(a){
delete a; //SyntaxError
}
delete foo; //SyntaxError
}());
20.5.3 매개변수 이름의 중복
(function(){
'use strict';
//SyntaxError
functin foo(x, x){
return x + x;
}
console.log(foo(1, 2));
}());
20.5.4 with문의 사용 : with문 사용시 SyntaxError
with문은 전달된 객체를 스코프체인에 추구하므로 동일한 객체의 프로퍼티 반복사용시 객체이름 생략으로 코드가 간단해지나 성능과 가독성 문제로 권장x
(function(){
'use strict';
//SyntaxError
with({ x:1 }
console.log(x);
}
}());
20.6 strict mode 적용에 대한 변화
20.6.1 일반함수의 this : strict mode에서 함수를 일반 함수로 호출시 this에 undefined가 바인딩됨, 일반함수내부에서는 this가 불필요하므로(에러는 발생x)
(function(){
'use strict';
//일반함수
function foo(){
console.log(this); //undefined;
}
foo();
//생성자함수
function Foo(){
console.log(this); Foo
}
new Foo();
}());
20.6.2 arguments 객체 : strict mode에서는 매개변수에 전달된 인수를 재할당하여 변경해도 arguments객체에 반영x
(function (a){
'use strict';
//매개변수에 전달된 인수를 재할당하여 변경
a = 2;
//변경된 인수가 arguments객체에 반영되지 않음
console.log(arguments); //{ 0:1, length:1 }
}(1));
'JS > [책] 모던 JS deep dive' 카테고리의 다른 글
22장. this (0) | 2023.01.11 |
---|---|
21장. 빌트인 객체 (0) | 2023.01.10 |
18장. 함수와 일급 객체 (0) | 2022.12.21 |
15장. let, const 키워드와 블록레벨 스코프 (0) | 2022.12.21 |
11장. 원시값과 객체의 비교 (0) | 2022.12.14 |