Menu
CoddyTech

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.color 和 this.model 指的是该特定对象的变量。

创建一个汽车对象并设置它的变量:

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 类,添加一个名为 displayInfo 的方法,使用 this 关键字按以下格式打印汽车的年份、品牌和型号:

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

  • car.dart:包含 Car 类,你将在其中添加 displayInfo 方法
  • 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 在线编译器