[JS] THIS란?

짱효·2023년 10월 25일

JS

목록 보기
12/21

this의 값은 함수가 호출될때 결정됩니다.

const car ={
	name : 'KIA',
  	getName: function(){
    	console.log("car getName", this) //car객체가 나온다.
    }
}

car.getName(); // A가 b를 불렀다
const globalCar = car.getName;
globalCar() //window나옴.  b가 그냥 불렸음..밖에서 불렀는지, 밖에서 호출. 그래서 window가 불렀음


const car2 = {
 	name : 'hyundai',
  	getName: car.getName
}
car2.getName() //{name : 'hyundai',getName: car.getName}
//호출하는 애가 this가 된다.


const btn = document.getElementById("button");
btn.addEventListener("click", car.getName;);
//버튼 태그 그 자체가 나왔다. 버튼이 호출한거여~ this = 버튼이다.

.bind : this 값을 고정해준다.

const car2 = {
 	name : 'hyundai',
  	getName: car.getName
}
const bindGetName = car2.getName.bind(car) // KIA차가 나옴
//bind를 통해 값을 고정 가능.
const btn = document.getElementById("button");
btn.addEventListener("click", car.getName.bind(car);); 
//KIA로 바뀜

test

const testCar = {
  name: "benz",
  getName: function(){
  	console.log("getname", this);
    const innerFunc = function () {
      console.log("innerFunc", this); //window
    };
    innerFunc(); //앞에 부르는게 없다.
  },
};

testCar.gerName();

this와 화살표함수

  • 화살표 함수써서 innerFunc()의 값 testCar로 만들기
  • 화살표 함수에서의 this는 함수가 속해 있는 곳의 상위 this를 계승 받는다.
  • 일반함수와 화살표 함수의 this는 다르다.
  • 화살표함수는 속해있는 상위의 this를 가지고온다.
  • bind를 제공하지 않는다.
const testCar = {
  name: "benz",
  getName: function(){
  	console.log("getname", this);
    const innerFunc = () =>
      console.log("innerFunc", this); //testCar
    };
    innerFunc(); //앞에 부르는게 없다.
  },
};

testCar.gerName();

test

const ageTest = {
	unit:'살',
  	ageList:[10, 20, 30],
  	getAgeList: function(){
      const result = this.ageList.map((age)=>{
      return age + this.unit;
});
      
      console.log(result)
    }
}

나는 일반함수를 써야해? 화살표 함수를 써라

  • 일반함수를 쓰기 좋다. bind로 고정해줄 수 있다.
  • 안에 있는 함수는 화살표함수를 써라.

[출처] https://www.youtube.com/watch?v=tDZROpAdJ9w

profile
✨🌏확장해 나가는 프론트엔드 개발자입니다✏️

0개의 댓글