
function test(members){
this.members = members;
this.perform = function() {
setTimeout(function() {
this.members.forEach(function(member){
member.perform();
})
}, 1000)
}
}
var testcase1 = new test([
{
name : 'takuya',
perform : function() {
console.log('Sing : a e i o u')
}
}
]);
testcase1.perform();
//TypeError: Cannot read properties of undefined (reading 'forEach')
this.members.forEach의 this는 setTimeout 함수안의 펑션을 가르키지 test의 this를 가리키지 않는다.function test(members){
this.members = members;
this.perform = function() {
setTimeout(() => {
this.members.forEach(function(member){
member.perform();
})
}, 1000)
}
}
...
testcase1.perform(); // Sing : a e i o u
function test(members){
this.members = members;
this.perform = function() {
setTimeout(function() {
this.members.forEach(function(member){
member.perform();
})
}.bind(this), 1000) // bind 사용 펑션 끝에 붙여줌
}
}
...
testcase1.perform(); // Sing : a e i o u
function test(members){
var cur = this;
this.members = members;
this.perform = function() {
setTimeout(function() {
cur.members.forEach(function(member){
member.perform();
})
}, 1000)
}
}
...
testcase1.perform(); // Sing : a e i o u
const arr = [0,1,2,3,4];
for(var i=0; i<arr.length; i++){
setTimeout(function(){
console.log(i, arr[i]);
},i*1000);
}
//5 undefined 5 undefined 5 undefined 5 undefined 5 undefined
const arr = [0,1,2,3,4];
for(var i=0; i<arr.length; i++){
(function(index) {
setTimeout(function(){
console.log(index, arr[index]);
},i*1000);
})(i)
}
// 0 0, 1 1, 2 2, 3 3, 4 4
const arr = [0,1,2,3,4];
for(let i=0; i<arr.length; i++){
setTimeout(function(){
console.log(i, arr[i]);
},i*1000);
}
// 0 0, 1 1, 2 2, 3 3, 4 4
const arr = [0,1,2,3,4];
arr.forEach((item,i)=>{
setTimeout(()=> {
console.log(i, item);
}, i * 1000)
})
// 0 0, 1 1, 2 2, 3 3, 4 4
블록 수준 스코프란 ?
📌 if, for 등 block 구문 단위로 범위를 갖는다.
호이스팅
- var로 선언된 변수, 함수는 호이스팅이 일어난다. 실행될 때 function scope상 맨 위로 var 선언이 끌어올려진다.
- 함수 선언부 위로 끌어올려지기 때문에 값 할당 전에 호출될 수 있다.
- 이러한 점 때문에 예상치 못한 버그가 일어날 수 있다.
- let, const 에도 호이스팅은 일어나지만 TDZ(Temporary Dead Zone) 개념 덕분에 할당되기 전에 호출하면 에러가 발생한다.
function outter() {
const name = 'jth';
return function () {
console.log(name);
}
}
const printName = outter();
printName(); //js
함수와 함수가 선언된 어휘적 환경의 조합이라고도 한다.
function Counter() {
let count = 0;
function increase(){
count++; //내부 함수에서 외부 변수 값을 가져다 씀
}
function print(){
console.log(`count : ${count} `);
}
return {
increase,
print,
}
}
const test = Counter(); // test에는 리턴된 함수들만 들어가 있음
test.increase();
test.increase(); // count 변수 조작
test.print();
console.log(test.count); // count는 외부에서는 접근 불가
// count : 2 undefined