this
값은 함수를 호출한 방법 에 의해 결정된다.화살표 함수
에서의 this
는 함수가 속해 있는 곳의 상위 this
를 계승 받는다.this
를 쓰고 싶다면 일반 함수
를 사용하여 bind함수
를 이용한 예측 가능한 코드를 짜고, 함수 안에 있는 함수의 경우 상위에 있는 것을 그대로 받아 오는 경우가 많기 때문에 화살표 함수
를 사용하는 것이 좋다.
⭐️
this
값은 함수를 호출한 방법 에 의해 결정된다.
const car = {
name : 'KIA',
getName : function(){
console.log('car getName', this);
},
};
// A.b(); A에 속한 b를 부른 형태.
car.getName();
// car getName {name: 'KIA', getName: ƒ}
const car2 = {
name : 'Hyundai',
getName : car.getName,
}
car2.getName();
//car getName {name: 'Hyundai', getName: ƒ}
car2
에서 부른 getName
이므로 this
는 함수를 호출한 car2
(함수를 호출한 것) 가 된다.
⭐️ 정리 ⭐️ 현재 실행 콘텍스트 기준 가장 가까운 상위 object 타입 레퍼런스
const globalCar = car.getName;
globalCar();
// car getName Window {window: Window, self: Window, document: document, name: '', location: Location, …}
globalCar();
는 어디에 속한 객체를 불렀는지 알 수 없는 상태이기 때문에 밖에 있는 객체 중 최상단의 window 객체가 this
가 된다.
이러한 문제점을 해결하기 위해 this
의 값을 고정시켜 줄 수 있는 bind
함수를 사용한다.
const obj2 = { c: 'd' };
function b() {
console.log(this);
}
b(); // Window
b.bind(obj2).call(); // obj2
b.call(obj2); // obj2
b.apply(obj2); // obj2
const bindGetname = car2.getName.bind(car);
bindGetname();
// car getName {name: 'KIA', getName: ƒ}
bind
를 통해서 값을 고정시켜 줄 수 있다.
bind
를 이용하여 위의 예제2 오류도 해결할 수 있다.
이벤트가 발생할 때, 내부적으로 this가 바뀌기 때문에 동작을 외울 수밖에 없다.
document.body.onclick = function() {
console.log(this); // <body>
}
$('div').on('click', function() {
console.log(this);
});
bind
를 쓰지 않아도 내부적으로 function
을 호출할 때 this
를 바꿔 'div'
가 된다.
$('div').on('click', function() {
console.log(this); // <div>
function inner() {
console.log('inner', this); // inner Window
}
inner();
});
예제3 을 해결하려면, this
를 저장하는 변수를 만들어 사용한다.
$('div').on('click', function() {
console.log(this); // <div>
var that = this;
function inner() {
console.log('inner', that); // inner <div>
}
inner();
});
또는 화살표 함수(Arrow Function)
을 사용한다.
$('div').on('click', function() {
console.log(this); // <div>
const inner = () => {
console.log('inner', this); // inner <div>
}
inner();
});
⭐️
화살표 함수
에서의this
는 함수가 속해 있는 곳의상위 this
를 계승 받는다.
⭐️화살표 함수
에서는bind
함수를 사용할 수없다.
원하는 결과값이 나오도록 코드를 수정하시오.
🙆🏻♂️ 원하는 결과값 : ['10살', '20살', '30살']
const ageTest = {
unit : '살',
ageList : [10, 20, 30],
getAgeList : function() {
const result = this.ageList.map(function(age) {
return age + this.unit;
});
console.log(result);
},
};
ageTest.getAgeList(); // 🙅🏻♂️ (3)[NaN, NaN, NaN]
const ageTest = {
unit : '살',
ageList : [10, 20, 30],
getAgeList : function() {
const result = this.ageList.map((age) => age + this.unit);
console.log(result);
},
};
ageTest.getAgeList(); // (3) ['10살', '20살', '30살']
📢 해당 글은 아래 글과 영상을 인용하여 정리하였습니다.
🔗 제로초 님 블로그 : 자바스크립트의 this는 무엇인가?
🔗 코딩알려주는누나 님 유튜브 : 개발자 면접 단골질문 자바스크립트 this