본문 바로가기

공부/JavaScript

Class - this 바인딩

# 01. 클래스 안의 함수

Class 안의 함수를 인자로 전달할 때 해당 class와 함수를 바인딩 해줘야 정상적으로 작동함.

 

예시)

class Food {
    constructor(name, emoji) {
        this.name = name;
        this.emoji = emoji;
        body.addEventListener('click', this.onClick);
    }
    onClick = (event) =>{
        const target = event.target;
        if(target.matches('#egg')){
            this.func && this.func('egg');
        }else{
            this.func && this.func('food');
        }
    }
    setClickListener(func){
        this.func = func;
    }
    make(){
        const item = document.createElement('div');
        item.id = this.name;
        item.className = 'food';
        item.innerHTML = `${this.emoji}`;
        body.appendChild(item);
    }
}

 

this.onClick 을 'click'과 바인딩 해주는 작업이 필요하다.

 

 

 

1. Constructor 안에 새로운 라인 추가

 

this.onClick = this.onClick.bind(this);
body.addEventListener('click', this.onClick);

 

2. Constructor 안에 기존 라인 변경 

 

body.addEventListener('click', (event) => this.onClick(event));

 

3. Constructor 밖 해당 함수 변경

- 클래스 안의 함수를 다른 콜백으로 전달할때 가장 자주 사용되는 방법

- 해당 함수를 변수로 만들기

 

onClick = (event) =>{
    const target = event.target;
    
    ...
}

'공부 > JavaScript' 카테고리의 다른 글

논리 연산자 (Logical Operator)  (0) 2022.12.15
reduce 배열에서 쓸 수 있는 고차함수  (0) 2022.11.11
Truthy & Falsy  (0) 2022.09.12
async, await  (0) 2022.09.01
Promise  (0) 2022.09.01