arrow function의 this

이용원·2022년 11월 18일
0

JAVASCRIPT

목록 보기
21/34

일반함수와 arrowfunction의 this

일반함수와 arrowfunction의 this는 가르키는 것이 다르다.

const person = {
    firstName :'Viggo',
    lastName :'Mortensen',
    fullName : function(){
        //여기서의  this는 person{}를 가르킴
        console.log(this);
      /*
      {
  		firstName: 'Viggo',
  		lastName: 'Mortensen',
  		fullName: [Function: fullName],
  		fullName2: [Function: fullName2]
	}
      */
        return `${this.firstName} ${this.lastName}`
    },

    fullName2 :()=>{
      	//arrow function의 this는 window를 가르킴
        console.log(this); // window
      /*
      [object Window]
      */
      
        return `${this.firstName} ${this.lastName}`

    }
}
//일반함수 메소드인 경우에는 this키워드가 왼쪽에 있는 객체를 가르킴
console.log(person.fullName()); //Viggo Mortensen

//arrowfunction 메소드인 경우에는 
console.log(person.fullName2()); //undefined undefined


더 깊게 들어가지 말고 지금은  객체에서 메소드를 만들 때 
arrow function을 사용하지 말고 일반함수로 메소드를 만들기로 합시다.

0개의 댓글

관련 채용 정보