자바스크립트 this !! ** 함수나 변수를 전역공간에서 만들면 {window} 에 보관한다.
console.log(this);
>> window
function 함수() {
console.log(this);
}
object
나를 포함한 오브젝트가 this를 뜻한다.
오브젝트{} 내 함수안에 쓰면 그 함수를 가지고 있는 오브젝트를 뜻한다.
let 오브젝트 = {
data: 'kim',
함수: function () {
console.log(this);
}
};
오브젝트.함수();
>> {data: "kim", 함수: ƒ}
let 오브젝트 = {
data: {
함수: function () {
console.log(this);
}
},
};
오브젝트.data.함수();
>> {함수: ƒ}
this 값을 함수 밖에서 있는거 그대로 씀.
내부 this 값을 변화 하지 않고 외부에 있는 this 값을 그대로 씀.
console.log(this);
let 오브젝트 = {
data: {
함수: () => {
console.log(this);
},
},
};
오브젝트.data.함수();
>> Window
let 오브젝트 = {
이름들: ['앨', '리', '스'],
함수: function () {
console.log(this);
오브젝트.이름들.forEach(() => {
console.log(this);
});
},
};
오브젝트.함수();
>>
{이름들: Array(3), 함수: ƒ}
{이름들: Array(3), 함수: ƒ}
{이름들: Array(3), 함수: ƒ}
{이름들: Array(3), 함수: ƒ}
여기서의 this는 기계로부터 새로 생성될 오브젝트 를 의미한다.
function 기계(){
this.이름 = 'Kim';
}
tip: new 키워드를 사용하면 새로운 오브젝트를 꺼낼 수가 있다.
새로운 오브젝트 값은 {이름: 'Kim'}이라는 값을 가지고 있다.(this 라는 키워드 때문에)
function 기계(){
this.이름 = 'Kim'
}
let 오브젝트 = new 기계();
document.getElementById('버튼').addEventListener('click', function(e){
console.log(this);
console.log(e.currentTarget); this 와 같은 뜻.
});
>> 이벤트가 동작하고 있는 곳 <button id="버튼"></button>
case. 1 - 이벤트리스너 안에 콜백함수를 쓴다면?
window 출력
이벤터 리스너 안에 함수를 썼기때문에 의미가 변한다.
아무 역할 없는 콜백함수는 일반함수랑 같기 때문에.
document.getElementById('버튼').addEventListener('click', function(e){
let 어레이 = [1,2,3];
어레이.forEach(function(a){
console.log(this)
});
});
case. 2 - 오브젝트 안에 콜백함수를 쓴다면?
window 출력
forEach() 안에 있는 함수는 특별한 역할을 하는 함수가 아니기 때문에.
let 오브젝트 = {
이름들 : ['김', '이', '박'];
함수 : function(){
오브젝트.이름들.forEach(function(){
console.log(this)
});
}
}
this 값은 function을 만날때 마다 바뀔수 있기 때문에 내가 원하는 this를 쓰려면 arrow function 을 쓰면 된다.
let 오브젝트 = {
이름들 : ['김', '이', '박'];
함수 : function(){
오브젝트.이름들.forEach(() => {
console.log(this)
});
}
}
>>
{이름들: Array(3), 함수: ƒ}
{이름들: Array(3), 함수: ƒ}
{이름들: Array(3), 함수: ƒ}
{이름들: Array(3), 함수: ƒ}