this와 화살표 함수의 관계
화살표 함수의 this는 자신만의 this를 갖지 않고, 외부(상위) 스코프의 this를 그대로 사용합니다.
기본 함수와 this
const obj = {
name: 'Jane',
sayHello: function () {
console.log(this.name); // "Jane"
}
};
obj.sayHello();
화살표 함수와 this
const obj = {
name: 'Jane',
sayHello: () => {
console.log(this.name); // ❌ undefined (또는 window.name)
}
};
obj.sayHello();
function Person(name) {
this.name = name;
// 일반 함수 사용 시 문제 발생
setTimeout(function () {
console.log('Hello, ' + this.name); // ❌ undefined (this는 window)
}, 1000);
}
new Person('Jane');
function Person(name) {
this.name = name;
// 화살표 함수
setTimeout(() => {
console.log('Hello, ' + this.name); // ✅ "Jane"
}, 1000);
}
new Person('Jane');
Vue2 에서의 예
export default {
data() {
return {
count: 0
};
},
methods: {
increaseLater() {
setTimeout(function () {
this.count++; // ❌ 작동 안 함 (this는 window)
}, 1000);
},
increaseLaterArrow() {
setTimeout(() => {
this.count++; // ✅ 작동함 (this는 Vue 인스턴스)
}, 1000);
}
}
};
Vue 3 Options API에서 this vs 화살표 함수
export default {
data() {
return {
count: 0
};
},
methods: {
increaseLater() {
setTimeout(function () {
this.count++; // ❌ 작동 안 함 (this는 window 또는 undefined)
}, 1000);
},
increaseLaterArrow() {
setTimeout(() => {
this.count++; // ✅ 작동함 (this는 Vue 인스턴스)
}, 1000);
}
}
};
Vue 3 Composition API에서는 this를 거의 안 씀!
<script setup>
import { ref } from 'vue';
const count = ref(0);
function increaseLater() {
setTimeout(() => {
count.value++; // ✅ this 없이도 사용 가능
}, 1000);
}
</script>
<template>
<button @click="increaseLater">증가</button>
<p>{{ count }}</p>
</template>
클래스 컴포넌트
Vue 2.x~3.x에서 TypeScript와 함께 **데코레이터(decorator)**를 사용하는 vue-class-component 방식의 코드 스타일입니다.
Composition API가 도입된 이후 주류 방식은 아닙니다.
그러나 TypeScript와 객체지향 패턴을 선호하는 개발자들에게는 여전히 유용하게 쓰이고 있습니다.
Vue 인스턴스를 ES6 클래스 문법으로 정의하고, 데코레이터를 사용해 속성, 메서드, props 등을 명시하는 방식입니다.
import { Vue, Options } from 'vue-class-component';
@Options({
props: ['title']
})
export default class MyComponent extends Vue {
count = 0;
increment() {
this.count++;
}
}
incrementLater = () => {
setTimeout(() => {
this.count++; // ✅ 작동
}, 1000);
}
import { Vue } from 'vue-class-component';
export default class TimerComponent extends Vue {
count = 0;
startTimer() {
setTimeout(() => {
this.count++; // ✅ 안전
}, 1000);
}
}'Javascript' 카테고리의 다른 글
| 자바스크립트 공부6 - JS 모듈 시스템, 조건문과 삼항 연산자 (1) | 2025.06.25 |
|---|---|
| 자바스크립트 공부4 - 비동기 처리 (1) | 2025.05.29 |
| 자바스크립트 공부3 - 배열과 객체 다루기 (1) | 2025.05.27 |
| 자바스크립트 공부2 - 함수 (1) | 2025.05.16 |
| 자바스크립트 공부1 - ES6 문법 정리 (1) | 2025.05.15 |