this ?
어떻게 실행 되나요?
이처럼 각각 실행에 따라서 this는 다르게 결정된다.
Method를 호출할 때 this의 값
new 키워드를 이용해 생성자를 호출할 때
call, apply를 호출할 때
👀 this 주의사항
화살표 함수에서 this는 사용하지 말자.
화살표 함수는 this를 결정하지 않는다!
this를 사용하고 싶다면 일반함수를 이용하자
.call .apply .bind ?
call 메소드
apply 메소드
call과 apply 예제
const nike = {
name : "Nike"
}
const adidas = {
name : "Adidas"
}
function showBrand(){
console.log(this.name);
}
function update(price,category){
this.price = price;
this.category = category;
update.call(nike, 20000, "Shoes"); // call은 2번째 인자부터 직접 받는다.
console.log(nike); // {name : "Nike", price : 20000, category : "Shoes"}
update.apply(adidas,[30000, "T-shirt"]); // apply는 2번째 인자부터 배열로 받는다.
console.log(adidas); // {name : "Adidas", price : 30000, category : "T-shirt"}
bind 메소드
const nike = {
name : "Nike"
}
const adidas = {
name : "Adidas"
}
function showBrand(){
console.log(this.name);
}
function update(price,category){
this.price = price;
this.category = category;
updateNike = update.bind(nike); // 이 함수는 항상 nike를 this로 받는다.
updateNike(40000, 'Shoes'); // {name : "Nike", price : 40000, category : "Shoes"}