1. this는 호출한 위치에 따라 전역을 바라볼수도 있고 object를 바라 볼수 있다
2. 전역에서 this 호출 시 window 객체를 가리킨다.
console.log(this)
3.호출 되는 시점의 호출한 object가 this가 된다.
- objectB.funA() 호출시 호출한 object가 objectB 이기 때문에 this는 objectB 이다. objectB.a 값이 찍힌다.
let objectB={
a:30,
funA: function(){
console.log(this.a);
},
}
objectB.funA()
- objectB에서 만든 함수라도 objectA.funA() 호출시 호출한 object가 objectA 이기 때문에 this는 objectA 이다. objectA.a 100값이 찍힌다.
let objectB={
a:30,
funA: function(){
console.log(this.a);
},
}
let objectA={
a:100
}
objectA.funA=objectB.funA;
objectA.funA();
4. 화살표 함수의 this
- 화살표 함수는 호출 되는 시점의 object가 this가 아닌 호출 되는 바깥 스코프에서 this 의 값을 계승받는다
- testA() 호출 시 forEach에 의해 화살표 함수 사용 시 안에 있는 this는 this로 부터 바깥 스코프인 teatA 안에 this를 계승 받아 objectTest가 된다.
- testB() 호출 시 this로 부터 바깥 스코프는 objectTest 스코프가 되기때문에 여기서 this를 호출 시 window이며 this는 window가 되다.
let objectTest={
a:10,
b:100,
arrayNumber: [3,2,1],
testA: function(){
this.arrayNumber.forEach(element => {
console.log(this);
});
},
testB:()=>{
console.log(this);
},
}
objectTest.testA();
objectTest.testB();