On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. this Means "the Current Object"
  4. 2. When a Parameter Hides a Field
  5. 3. this in Constructors
  6. 4. Passing and Returning this
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 033: The this Keyword

Day11: Classes, Objects & Constructors
Lecture033 of 057
Estimated video length10 min
TargetDart 3.12
LevelBeginner

Inside a method, how does an object refer to itself? With this. You've already used this.name in constructors. This lecture explains what this really is, when you must write it, and the classic bug when you forget.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 030–032 (classes, constructors and constructor parameters).


Learning Objectives

  • Explain that this means "the object this code is running on"
  • Use this.field when a parameter has the same name as a field
  • Understand this.field in constructor parameters
  • Pass or return the current object with this

1. this Means "the Current Object"

When r.resize(...) runs, this inside resize is r. When other.resize(...) runs, this is other. It's how a method talks about its own object.

2. When a Parameter Hides a Field

If a parameter has the same name as a field, the plain name means the parameter. Write this. to reach the field:

dart
class Rectangle {
  double width;
  double height;

  Rectangle(this.width, this.height);

  void resize(double width, double height) {
    this.width = width;     // field = parameter
    this.height = height;
  }

  double area() => width * height;   // no clash here, so no `this` needed
}

var r = Rectangle(2, 3);
print(r.area());   // 6.0
r.resize(4, 5);
print(r.area());   // 20.0

When there's no name clash, width and this.width mean the same thing, and Dart style is to leave this out.

3. this in Constructors

Rectangle(this.width, this.height) is a shortcut for:

dart
Rectangle(double width, double height)
    : width = width,
      height = height;

this.width in the brackets means "this parameter goes straight into the width field".

4. Passing and Returning this

this is a normal value. You can compare it, pass it to a function, or return it:

dart
bool isBiggerThan(Rectangle other) => this.area() > other.area();

print(r.isBiggerThan(Rectangle(1, 1)));   // true

Returning this lets calls be chained:

dart
class Counter {
  int count = 0;
  Counter increment() {
    count++;
    return this;
  }
}

var c = Counter();
c.increment().increment().increment();
print(c.count);   // 3

(This is the idea behind the Builder class in Lecture 051.)


Code Examples

Example 1: Players and Levels

dart
class Player {
  String name;
  int score;
  int level;

  Player(this.name, {this.score = 0, this.level = 1});

  void addPoints(int points) {
    this.score += points;
    if (score >= level * 100) {
      level++;
      print('$name reached level $level!');
    }
  }

  bool isAheadOf(Player other) => score > other.score;

  void compare(Player other) {
    var leader = isAheadOf(other) ? this : other;
    print('${leader.name} is leading with ${leader.score} points');
  }
}

void main() {
  var a = Player('Ali');
  var s = Player('Sara', score: 40);
  a.addPoints(70);
  s.addPoints(70);
  a.compare(s);
  a.addPoints(60);
  a.compare(s);
}

Output

code
Sara reached level 2!
Sara is leading with 110 points
Ali reached level 2!
Ali is leading with 130 points

In compare, this is the player the method was called on (a), and other is the one passed in (s). The ternary picks whichever is ahead.


Common Beginner Mistakes

1. Forgetting this when names clash

dart
class Rectangle {
  double width = 0;
  void resize(double width) {
    width = width;
  }
}

var r = Rectangle();
r.resize(10);
print(r.width);   // 0.0

No error, but the field never changes! width = width copies the parameter into itself. Write this.width = width;.

2. Using this outside a class

dart
void main() {
  print(this);
}
code
Error: Expected identifier, but got 'this'.

main doesn't belong to any object, so there's no "this" to refer to.

3. Writing this. everywhere: it isn't wrong, but Dart style uses it only when it's needed (a name clash) or when it makes the code clearer.


Practice Questions

  1. In a.addPoints(10), what is this inside addPoints?
  2. Fix this setter method: void rename(String name) { name = name; }
  3. Is this.score += points different from score += points in the Player class?
  4. Why does return this; allow chaining?
  5. Can you use this inside main?

Practice Answers

  1. The object a.
  2. void rename(String name) { this.name = name; }
  3. No. There's no parameter called score, so both refer to the field.
  4. Each call gives back the same object, so the next method can be called on it.
  5. No. main isn't inside a class.

Key Takeaways

  • this is the object the current method is running on.
  • Use this.field when a parameter or local variable has the same name as a field.
  • this.field in a constructor's brackets assigns the argument to that field.
  • this can be passed, compared and returned (return this; enables chaining).
  • field = field without this is a silent bug.