On this page11 sections
Lecture 033: The this Keyword
| Day | 11: Classes, Objects & Constructors |
| Lecture | 033 of 057 |
| Estimated video length | 10 min |
| Target | Dart 3.12 |
| Level | Beginner |
Inside a method, how does an object refer to itself? With
this. You've already usedthis.namein constructors. This lecture explains whatthisreally 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
thismeans "the object this code is running on" - Use
this.fieldwhen a parameter has the same name as a field - Understand
this.fieldin 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:
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.0When 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:
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:
bool isBiggerThan(Rectangle other) => this.area() > other.area();
print(r.isBiggerThan(Rectangle(1, 1))); // trueReturning this lets calls be chained:
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
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
Sara reached level 2!
Sara is leading with 110 points
Ali reached level 2!
Ali is leading with 130 pointsIn 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
class Rectangle {
double width = 0;
void resize(double width) {
width = width;
}
}
var r = Rectangle();
r.resize(10);
print(r.width); // 0.0No error, but the field never changes! width = width copies the parameter into itself. Write
this.width = width;.
2. Using this outside a class
void main() {
print(this);
}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
- In
a.addPoints(10), what isthisinsideaddPoints? - Fix this setter method:
void rename(String name) { name = name; } - Is
this.score += pointsdifferent fromscore += pointsin the Player class? - Why does
return this;allow chaining? - Can you use
thisinsidemain?
Practice Answers
- The object
a. void rename(String name) { this.name = name; }- No. There's no parameter called
score, so both refer to the field. - Each call gives back the same object, so the next method can be called on it.
- No.
mainisn't inside a class.
Key Takeaways
thisis the object the current method is running on.- Use
this.fieldwhen a parameter or local variable has the same name as a field. this.fieldin a constructor's brackets assigns the argument to that field.thiscan be passed, compared and returned (return this;enables chaining).field = fieldwithoutthisis a silent bug.