JavaScript

this, 메서드 축약, 일반 함수 표현식

오류확인자 2024. 8. 29. 20:58

1. this

메서드로서 호출이 된다면, this는 그 메서드를 소유한 객체를 가리킨다.

독립적으로 호출되면, 함수가 객체와 분리되어 호출되면 this는 전역객체(브라우저에서는 window, node.js에서는 global)를 가리킨다. 엄격모드(strict mode)는 this가 undefined 가 된다.

 

1-1. 일반 함수 표현식

const obj = {
    myMethod: function() {
        console.log(this);
    }
};

// obj.myMethod()를 호출하면:
obj.myMethod(); // 'this'는 obj를 가리킨다.

// 그러나 메서드를 변수에 할당한 후 호출하면:
const myFunction = obj.myMethod;
myFunction(); // 'this'는 전역 객체를 가리킨다.

 

obj.myMethod()를 호출하면 this는 obj를 가리킨다. 이는 메서드가 객체의 맥락에서 호출되었기 때문이다.

근데 myMethod를 변수 myFunction에 할당되고, 독립적으로 myFunction() 호출 할 경우 

더이상 this는 더이상 obj를 가리키지 않고, 전역 객체를 가리키게 된다.

1-2. 메서드 축약형

const obj = {
    myMethod() {
        console.log(this);
    }
};

// obj.myMethod()를 호출하면:
obj.myMethod(); // 'this'는 obj를 가리킨다.

// 그러나 메서드를 변수에 할당한 후 호출하면:
const myFunction = obj.myMethod;
myFunction(); // 'this'는 전역 객체를 가리킨다.

 

메서드 축약형에서도 동일한 원칙으로 적용된다. obj.myMethod()를 호출할 때는 this가 obj를 가리킨다.

하지만 myMthod를 변수 myFunction에 할당 한 후 독립적으로 호출하면, this는 여전히 전역 객체를 가리키게 된다.