Menu
CoddyTech

this 키워드

Coddy Dart 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 110개 중 5번째.

this 키워드는 class의 현재 instance를 가리킵니다. method 내부에서 this를 사용하면 객체 자체의 variable에 액세스할 수 있습니다.

다음은 this를 사용하는 method가 있는 class의 예입니다:

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 Sedan

this는 메서드 parameter가 instance variable과 같은 이름을 가질 때 특히 유용합니다:

class Car {
  String color = '';

  void setColor(String color) {
    this.color = color; // this.color = 인스턴스 변수, color = 매개변수
  }
}

this가 없다면 Dart는 color가 parameter를 가리키는지 아니면 instance variable을 가리키는지 알 수 없습니다. 핵심 요점: this는 항상 현재 method를 호출하고 있는 특정 object를 가리킵니다.

challenge icon

챌린지

쉬움

car.dart의 Car 클래스를 완성하세요. this 키워드를 사용하여 자동차의 연도, 제조사, 모델을 다음 형식으로 출력하는 displayInfo라는 메서드를 추가해야 합니다:

'This car is a [year] [make] [model]'

  • car.dart: displayInfo 메서드를 추가할 Car 클래스가 포함되어 있습니다
  • driver.dart: 자동차 객체의 변수를 설정하고 displayInfo()를 호출합니다(잠김)

직접 해보기

import 'car.dart';

void main() {
  Car myCar = Car();
  myCar.year = '2020';
  myCar.make = 'Toyota';
  myCar.model = 'Corolla';
  myCar.displayInfo();
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Dart 컴파일러