Dart
this
Learn to access the class itself with this.
The this keyword
this means 'this instance' inside a method. It is most used in constructors when a parameter shares a name with a field. Example: User(String name) { this.name = name; }.
Here name refers to the parameter, this.name to the field. Without this the two names clash; the assignment would not happen. So this is required as a disambiguator.
If the names differ, this is unnecessary: User(String n) { name = n; }. But Dart prefers the short form User(this.name), which already embeds this. this earns its place in the long form.
this and the short form
this can be written explicitly or used implicitly through Dart's short constructor form. User(this.name) is the same as User(String name) { this.name = name; }, just shorter.
The short form works when the parameter name matches the field. When they differ, use the long form. Example: User(String fullName) { name = fullName; } — here this is not required.
In practice Dart developers prefer the short form. It is less code and makes this automatic. The long form is essential when extra logic (validation, for example) is needed.
Exercise Assign with this
Define a User class with a String name field. In the constructor User(String name) body, perform this.name = name. Inside main create a User('Ayşe') instance and print it with print(u.name).
Show example solution
class User {
String name;
User(String name) {
this.name = name;
}
}
void main() {
var u = User('Ayşe');
print(u.name);
}
Test yourself
-
What does this.name = name do?
- Assigns the name field to the name parameter
- Deletes both
- Throws an error
- Assigns the name parameter to the name field
Show answer
Assigns the name parameter to the name field — this.name is the field, name is the parameter; the field gets the value.
-
Using this
class User {
String name;
User(String name) {
____ = name;
}
}
Show answer
class User {
String name;
User(String name) {
this.name = name;
}
}
-
Match the this concepts
- this
- This instance
- this.name
- Field
- name
- Parameter ( in constructor )
- this.name = name
- Assignment
Next lesson: Summary - Class basics