this 키워드
Coddy Dart 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 110개 중 5번째.
this 키워드는 클래스의 현재 인스턴스를 가리킵니다. 메서드 내부에서 this를 사용하면 객체 자신의 변수에 접근할 수 있습니다.
다음은 this를 사용하는 메서드가 포함된 클래스의 예입니다:
class Car {
String color = '';
String model = '';
void honk() {
print('Beep beep!');
}
void describe() {
print('I am a ${this.color} ${this.model}');
}
}describe() 내부에서 this.color와 this.model은 해당 특정 객체의 변수를 가리킵니다.
자동차 객체를 생성하고 변수를 설정합니다:
Car myCar = Car();
myCar.color = 'Red';
myCar.model = 'Sedan';메서드를 호출합니다:
myCar.honk();
myCar.describe();출력:
Beep beep!
I am a Red Sedanthis는 메서드 매개변수의 이름이 인스턴스 변수의 이름과 같을 때 특히 유용합니다:
class Car {
String color = '';
void setColor(String color) {
this.color = color; // this.color = 인스턴스 변수, color = 매개변수
}
}this가 없으면 Dart는 color가 매개변수를 가리키는지 아니면 인스턴스 변수를 가리키는지 알 수 없습니다. 핵심 포인트: this는 항상 현재 메서드를 호출하고 있는 특정 객체를 가리킵니다.
챌린지
쉬움car.dart 파일에 있는 Car 클래스를 완성하세요. this 키워드를 사용하여 자동차의 연식(year), 제조사(make), 모델(model)을 다음 형식으로 출력하는 displayInfo 메서드를 추가해야 합니다:
'This car is a [year] [make] [model]'
car.dart:displayInfo메서드를 추가할Car클래스가 포함되어 있습니다.driver.dart: 자동차 객체의 변수를 설정하고displayInfo()를 호출합니다. (수정 불가)
치트 시트
this 키워드는 클래스의 현재 인스턴스를 참조하며 메서드 내부에서 객체 자신의 변수에 접근할 수 있게 해줍니다.
메서드에서 this 사용하기:
class Car {
String color = '';
String model = '';
void describe() {
print('I am a ${this.color} ${this.model}');
}
}this는 메서드 매개변수가 인스턴스 변수와 동일한 이름을 가질 때 특히 유용합니다:
class Car {
String color = '';
void setColor(String color) {
this.color = color; // this.color = 인스턴스 변수, color = 매개변수
}
}this가 없으면 Dart는 color가 매개변수를 가리키는지 아니면 인스턴스 변수를 가리키는지 알 수 없습니다.
직접 해보기
import 'car.dart';
void main() {
Car myCar = Car();
myCar.year = '2020';
myCar.make = 'Toyota';
myCar.model = 'Corolla';
myCar.displayInfo();
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.