This란?

미어캣의 개발일지·2023년 6월 19일
0
post-thumbnail

📕This란?

대부분의 경우 this의 값은 함수를 호출한 방법이 결정합니다.
실행하는 중 할당으로 설정할 수 없고 함수를 호출할 때 마다 다를 수 있습니다.
-MDN 문서-




📕전역 범위

일반적으로 this를 호출한다면, thiswindow라는 전역 객체를 가리킴
(Node.js에서는 Global)


console.log(this === window); // true



📕함수 범위

함수 내부에서 this의 값은 함수를 호출한 방법에 의해 좌우됩니다.


📖단순 호출

function func() {
    return this;
}

func() === window; // true

📖객체의 메소드(Method)

const car = {
    name: "KIA",
    getName: function () {
        console.log(this.name);
    },
};

car.getName(); //KIA
const car2 = {
    name: "Hyundai",
    getName: car.getName,
};

car2.getName(); // Hyundai
const bindGetname = car2.getName.bind(car);
bindGetname(); // KIA
const testCar = {
    name: "benz",
    getName: function () {
        console.log(this.name); // benz
        const innerFunc = function () {
            console.log(this.name); //undefined
        };
        // 화살표 함수에서의this는 함수가 속해있는곳의 상위 this를 계승 받는다.
        const innerFunc2 = () => {
            console.log(this.name); //benz
        };
        innerFunc();
        innerFunc2();
    },
};
testCar.getName();

참조

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/this
https://hanamon.kr/javascript-this%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C/
https://www.youtube.com/watch?v=tDZROpAdJ9w&t=449s

profile
이게 왜 안되지? 이게 왜 되지?

0개의 댓글