일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- JavaScript
- 동전 0
- 부트캠프항해
- 배열 메소드
- 알고리즘
- greedy
- NextJS v13
- 자바스크립트
- 실전프로젝트
- 배열 중복 제거
- 중복선택
- server component
- 서버 컴포넌트
- 항해99솔직후기
- 탐욕알고리즘
- 그리디
- 카테고리필터
- 클라이언트 컴포넌트
- 항해99후기
- db수정
- jQuery
- 숫자를 별점으로
- 날씨 api
- 백준
- 중복카테고리
- 항해99
- react
- 로딩 후 실행
- 프로그래머스
- 항해99추천
- Today
- Total
공부 및 일상기록
[Javascript] this 간단히 정리해보기 본문
다른 언어에서의 this와 자바스크립트의 this는 많이 다르다고 한다.
하지만 나는 자바스크립트에서만 사용해봐서 사실 크게 체감하지는 못한다.
다만.. 너무 어렵다고만 느껴왔던것 같아서 다시 한번 정리해 본다.
** 여기서 사용되는 변수, 함수, 클래스에 사용된 이름은 아무 의미가 없고, 변수명이 떠오르지 않아 사용한 것 뿐입니다..
1. 브라우저 환경에서 this를 바로 호출해보기
console.log(this) //Window
브라우저 환경에서 this를 호출하면 window객체가 보이게 될 것이다.
그 이유는 자바스크립트에서 기본 컨텍스트가 전역 컨텍스트, 즉 전역 객체이기 때문이다.
브라우저에서 전역객체는 window 객체이다.
2. 함수 안에 this를 넣고 호출해보기
function simpleFunc() {
console.log(this);
}
simpleFunc(); //윈도우 객체
이 경우에도 역시 window객체가 보이게 된다.
왜 그런 것일까?
일단 호출 방식을 이해해봐야 한다.
현재 함수는 어떤 객체의 메서드가 아니라 곧바로 정의된 함수이다.
사실 이렇게 정의 된 함수들은 모두 전역객체에 속하게 된다.
따라서 simpleFunc() 을 실행하게 되면 전역 객체가 호출한 것이기 때문에 this 는 윈도우가 되는 것이다.
3. 생성자 안에서 불러보기
class SimpleClass {
simpleMethod = function () {
console.log(this);
};
}
const simpleClass = new SimpleClass();
simpleClass.simpleMethod(); //SimpleClass 객체
일단 SimpleClass라는 클래스를 만들고, 내부에 simpleMethod라는 메서드를 정의했다.
그리고 그 클래스를 가지고 simpleClass라는 인스턴스를 생성했다. (인스턴스란 클래스로부터 생성된 객체를 의미한다.)
그리고 simpleClass.simpleMethod()를 실행하게 되면 SimpleClass 객체를 보이게 된다.
이제는 window가 아닌 simpleClass 객체가 simpleMethod를 호출하였기 때문에 this는 simpleClass객체를 보여주는 것이다.
4. 생성된 인스턴스를 변수에 할당해서 사용해보기
class SimpleClass {
simpleMethod = function () {
console.log(this);
};
}
const simpleClass = new SimpleClass();
simpleClass.simpleMethod(); //SimpleClass 객체
const isInherited = simpleClass.simpleMethod;
isInherited(); //undefined
3번 예제에서 isInherited라는 변수에 simpleMethod를 직접 할당한 것이다.
이 경우 this는 undefined가 된다.
그 이유는 simpleMethod를 변수에 할당하게 되면서 ] simpleClass인스턴스와의 관계가 끊어지기 때문이다.
쉽게 생각해보면 인스턴스 내부의 메서드를 인스턴스를 이용해서 실행한 것이 아니라, 다른 변수에 인스턴스의 메서드를 직접 할당 하였는데 이 때 이 메서드는 더이상 simpleClass의 인스턴스가 아닌 독립적인 함수가 되는 것이다.
그럼 왜 undefined일까?
비 엄격모드에서 실행하게 되면 이 결과는 window객체가 된다. 어디에 속하지 않고 독립적인 함수는 window객체에 속하기 때문이다.
하지만 이렇게 예상하기 어려운 this의 변경은 코드작성에 어렵고 복잡해지기 때문에, 예측 가능한 동작을 위해 엄격 모드에서 undefined가 되는 것이다.
5. 다른 생성자의 메서드에 할당해서 사용해보기
class SimpleClass {
simpleMethod = function () {
console.log(this);
};
}
const simpleClass = new SimpleClass();
class UnSimpleClass {}
const unSimpleClass = new UnSimpleClass();
unSimpleClass.unSimpleMethod = simpleClass.simpleMethod;
unSimpleClass.unSimpleMethod(); //unSimpleClass
이번에는 UnSimpleClass를 하나 만들고, 해당 클래스로 만든 인스턴스의 메서드에 직접 simpleMethod를 할당해 봤다.
이 결과는 UnSimpleClass가 된다.
일단 위에서 변수에 할당할 때, 이미 독립적인 함수가 되는것을 확인 했다.
그와 마찬가지로 unSimpleClass인스턴스의 unSimpleMethod에 할당하게 되면, simpleMethod는 simpleClass와의 연결을 끊고 독립하게 되는데, 이 때, 전역에 존재하는 것이 아닌 unSimpleClass인스턴스에 존재하기 때문에 그런 결과가 나오는 것이다.
6. bind 메서드 사용해보기
class SimpleClass {
simpleMethod = function () {
console.log(this);
};
}
const simpleClass = new SimpleClass();
const bindMethod = simpleClass.simpleMethod.bind(simpleClass);
bindMethod(); //SimpleClass
4번 예제와 비슷하지만, 이번엔 bind메서드를 사용해서 직접 연결될 객체를 지정해줬다.
이렇게 bind를 사용하면 내가 연결할 객체를 지정할 수 있다.
7. Arrow function(화살표 함수)를 사용해서 bind해보기
class ALittleSimpleClass {
aLittleSimpleMethod = () => {
console.log(this);
};
}
const aLittleSimpleClass = new ALittleSimpleClass();
const isInheritedAndBinding = aLittleSimpleClass.aLittleSimpleMethod;
isInheritedAndBinding(); //ALittleSimpleClass
이번엔 클래스의 메서드를 정의할 때, function키워드가 아닌 화살표함수를 사용해서 작성해 보았다.
이렇게 하면 this는 항상 생성한 클래스에 bind된다.
'개발 > Javascript' 카테고리의 다른 글
[Typescript] 배열 사용하지 않고 Stack 구현하기 (0) | 2024.03.31 |
---|---|
매개변수와 인자의 차이 (0) | 2023.07.20 |
호이스팅이란? (0) | 2023.07.20 |
동기와 비동기 그리고 Promise와 async await (0) | 2023.05.03 |
[Typescript] 컴파일 세부설정 (tsconfig.json) (0) | 2023.01.25 |