Menu
Coddy logo textTech

thisキーワード

CoddyのDartジャーニー「オブジェクト指向プログラミング」セクションの一部 — レッスン 5/110。

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.colorthis.modelはその特定のオブジェクトの変数を参照します。

carオブジェクトを作成し、その変数を設定します:

Car myCar = Car();
myCar.color = 'Red';
myCar.model = 'Sedan';

メソッドを呼び出します:

myCar.honk();
myCar.describe();

出力:

Beep beep!
I am a Red Sedan

this は、メソッドのパラメータがインスタンス変数と同じ名前である場合に特に便利です。

class Car {
  String color = '';

  void setColor(String color) {
    this.color = color; // this.color = インスタンス変数, color = パラメータ
  }
}

this がなければ、Dart は color がパラメータを指しているのか、インスタンス変数を指しているのかを判断できません。重要なポイント:this は常に、現在メソッドを呼び出している特定のオブジェクトを指します。

challenge icon

チャレンジ

簡単

car.dart内のCarクラスに、thisキーワードを使用して車のyear、make、modelを以下の形式で出力するdisplayInfoという名前のメソッドを追加して、クラスを完成させてください。

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

  • car.dart: displayInfoメソッドを追加するCarクラスが含まれています。
  • driver.dart: carオブジェクトの変数を設定し、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();
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン