
1) strict mode
2) strict mode apply
function test(){
'use strict';
x = 10;
//코드의 선두가 아니면 strict mode 적용 불가
// use strict
}
test();
console.log(x);
/*
전역에 strict mode를 적용하면 스크립트 태그 단위로 적용되어 strict mode와 non strict mode의 혼용으로 인한
오류가 발생할 수 있다.
<script>
'use strict';
</scrict>
<script>
x = 10; // 에러 발생하지 않음
</script>
*/
// 서드 파티 라이브러리가 non strict mode인 경우 즉시 실행 함수로 스크립트 전체를 감싸서 스코프를 구분하고
// 즉시 실행 함수의 선두에 strict mode를 적용한다.
(function(){
'use strict';
// 작성 코드
})();
1) error example
(function(){
// 'use strict;'
x = 1;
console.log(x); //ReferenceError : x is not definec
});
(function(){
'use strict';
var x= 1;
//delete 연산자로 변수, 함수, 매개변수를 삭제하면 문법 에러 발생(객체의 프로퍼티 삭제 시 사용)
delete x;
})();
(function(){
'use strict';
function test(x, x){
return x + x;
}
})();
(function(){
// 'use strict';
const test = {x : 1, y : 2, z : 3};
// with는 객체 이름을 생략할 수 있어 코드를 간단하게 할 수 있다는 장점이 있지만
// 성능과 가독성이 나빠지는 문제로 사용하지 않는 것이 좋다.
with({test}){
console.log(x);
console.log(y);
console.log(z);
}
})();
2) change case
일반 함수의 this
생성자 함수가 아닌 일반 함수 내부에서는 this를 사용할 필요가 없기 때문에 strict mode에서는 함수를 일반 함수로 호출하면 this에 undefined가 바인딩 된다.
(function(){
'use strict'
function test(){
console.log(this);
}
test();
new test();
})();
arguments 객체
매개변수에 전달 된 인수를 재할당하여 변경해도 arguments 객체에 반영되지 않는다.
(function(x){
'use strict'
x = 2;
console.log(arguments);
})(1);