The Web Developer 부트캠프 2022

JS This

거위발바닥 2022. 9. 19. 19:37
const cat = {
    name: 'Blue Steele',
    color: 'grey',
    breed: 'scottish fold',
    meow() {
        console.log(this.color);
    }
}
 
위 코드로 cat.meow() 를 입력하면 meow함수의 console.log(this.color) 때문에
cat.color가 입력되어 grey가 출력된다. 여기서 this가 의미하는바는 const의 cat을 뜻한다.
즉, this.color는 cat의 프로퍼티인 color를 뜻한다. 
 
여기서 this는 cat.color중 color의 객체인 cat을 뜻한다. 그런데 만약 아래처럼 
 
const cat = {
    name: 'Blue Steele',
    color: 'grey',
    breed: 'scottish fold',
    meow() {
        console.log(this.color);
    }
}

const meow2 = cat.meow;
 
맨 밑의 meow2가 추가되어서 위의 cat 함수의 meow를 실행시킨다고 meow2()를 실행하면 에러가 발생한다.
그 이유는 this는 실행 명령어의 객체를 가르킨다. ( 처음의 cat.meow()의 this가 객체인 cat인 것 처럼 )
하지만 meow2()는 객체가 안보이기 때문에 모든 명령어의 기본 객체인 window를 this로 지정해서 문제가 발생한다.
( 보이지 않지만 원래는 window.meow2() ) 로 되있음
 
const hen = {
    name: 'Helen',
    eggCount: 0,
    layAnEgg() {
        this.eggCount++;
        return "EGG";
    }
}
 
this를 이용한 예이다. 
this.layAnEgg()를 입력하면 해당 함수인 this.eggCount++가 실행되어 hen.eggCount가 1 증가하고 EGG를 return한다.
이후 hen.eggCount를 입력하면 1이 나온다.
 
 
 
 
 

'The Web Developer 부트캠프 2022' 카테고리의 다른 글

JS forEach,MAP, Arrow  (0) 2022.09.20
JS Try Catch  (1) 2022.09.19
JS 함수를 변수로, 인수, return, 메서드  (0) 2022.09.19
JS BLOCK, var, lexical scope, 함수를 변수로  (0) 2022.09.19
JS SCOPE  (0) 2022.09.19